I'm a noob learning javascript. My tutor gave me this homework.
HOMEWORK: Write a function which takes an array of objects and a number, maxAge. Each object will have two properties: name, age. Return a new array of objects, only containing objects whose age is less or equal to maxAge.
Here's what I did:
const objectArray = [
firstObject = {
name: "Ryan",
age: 32
},
secondObject = {
name: "Caroline",
age: 1
},
thirdObject = {
name: "Steve",
age: 35
},
fourthObject = {
name: "Sheila",
age: 67
},
fifthObject = {
name: "Ron",
age: 67
},
sixthObject = {
name: "deadGuy",
age: 150
},
];
const maxAge = 67;
const makeAgeDiscrimArray = (objectArray) => {
const ageDiscrimArray = [];
const above67Array = [];
const length = objectArray.length;
for (let i = 0; i < objectArray.length; i++) {
if ((objectArray[i].age <= maxAge)) {
ageDiscrimArray.push(i)} else {
above67Array.push(i); // I know, it is a superfluity
}
}
return ageDiscrimArray;
};
console.log(makeAgeDiscrimArray(objectArray));
The function currently returns
[ 0, 1, 2, 3, 4 ]
I see what is happening, but I don't fully understand why.
Thanks in advance for your help!