Exercise 12 - Find the Oldest
Given an array of objects representing people with a birth and death year, return name the oldest person.
Hints
- this can be done with a couple of chained array methods, or by using
reduce.
I want to use reduce method
const people = [
{
name: 'Carly',
yearOfBirth: 1942,
yearOfDeath: 1970,
},
{
name: 'Ray',
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: 'Jane',
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
const findTheOldest = function (arr) {
const oldestPerson = arr.reduce((accumulator, next) => {
const age1 = accumulator.yearOfDeath - accumulator.yearOfBirth;
const age2 = next.yearOfDeath - next.yearOfBirth;
if (age1 > age2) {
return accumulator.name;
} else {
return next.name;
}
});
return oldestPerson;
};
console.log(findTheOldest(people));