Could someone help me understand why:
const people = [{
name: "Carly",
yearOfBirth: 1942,
yearOfDeath: 1970,
},
{
name: "Ray",
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: "Jane",
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
const findTheOldest = function(array) {
let alivePeople = array.filter(function(person) {
console.log(person.yearOfDeath);
if (person.yearOfDeath === true) {
console.log(person);
return true;
}
});
return alivePeople;
};
console.log(findTheOldest(people))
Is showing https://i.imgur.com/7qQXLJ0.png?
I was expecting it to return all the objects in the people array. I was trying to write code that would filter out people without a year of death.
3
Answers
Your code doesn’t work because
person.yearOfDeath
does not equaltrue
for any of the objects in the array.You should check whether each object has the
yearOfDeath
property, which can be done withObject.hasOwn
,Object#hasOwnProperty
, or thein
operator.Object.hasOwn
is recommended for modern code if there is no need to check the prototype chain.This does the job
Output
Its doing exactly as you asked it
Will filter out dead people this is not the what you want as its to filter out alive people