Reputation: 35
I don't know why this doesn't work...
function findOldest(list) {
let oldest = Math.max.apply(null, list.map(function(dev) { return
dev.age; }));
return list.filter((dev, age) => dev[age].includes(oldest));
}
I need to return only the oldest person or persons (if the oldest age matches). This is an example array:
[
{ firstName: 'Gabriel', country: 'Monaco', age: 49, language: 'PHP' },
{ firstName: 'Odval', country: 'Mongolia', age: 38, language: 'Python' },
{ firstName: 'Emilija', country: 'Lithuania', age: 19, language: 'Python' },
{ firstName: 'Sou', country: 'Japan', age: 49, language: 'PHP' },
]
With the above example, the function needs to return this:
[
{ firstName: 'Gabriel', country: 'Monaco', age: 49, language: 'PHP' },
{ firstName: 'Sou', country: 'Japan', age: 49, language: 'PHP' },
]
I've looked at ways reduce() might work here as well, with no success.
I'm learning, and this is my 1st question here... please be gentle. xD
I've looked up every tutorial and search terms I can think of to learn this on my own. I don't want to just get the answer, but also, I'm hoping to learn why/how it works.
Thank you for your time.
Upvotes: 3
Views: 3281
Reputation: 370769
list.filter((dev, age) => dev[age].includes(oldest))
doesn't make sense because age
is not an outer variable, but a plain property - and the value is a number, not an array, so .includes
won't work.
I'd use Math.max
to first identify the highest age, then filter
by the objects with that age.
const list = [
{ firstName: 'Gabriel', country: 'Monaco', age: 49, language: 'PHP' },
{ firstName: 'Odval', country: 'Mongolia', age: 38, language: 'Python' },
{ firstName: 'Emilija', country: 'Lithuania', age: 19, language: 'Python' },
{ firstName: 'Sou', country: 'Japan', age: 49, language: 'PHP' },
];
const findOldest = (list) => {
const maxAge = Math.max(...list.map(obj => obj.age));
return list.filter(obj => obj.age === maxAge);
};
console.log(findOldest(list));
Upvotes: 1