I have this array of Objects
const people = [
{
name: "Carly",
yearOfBirth: 1942,
yearOfDeath: 1970,
},
{
name: "Ray",
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: "Jane",
yearOfBirth: 1912,
yearOfDeath: 1941,
},
];
and I am trying to get the oldest person , I have tried to use reduce method like this
const totalyears = people.reduce(
(accumulator, age) => accumulator + age.yearOfDeath - age.yearOfBirth,
0
);
console.log(totalyears);
but what I get instead of individual values for each name I get back the result of the total yearofDeadth minus the total yearOfBirth , that is 106; but what I am looking for is to get back something like his "Ray is the oldest person he is 49 years old"
I also tried to apply this other code but I get back the year as the object like this
let peopleobject = people.reduce(function (accumulator, person) {
return { ...accumulator, [person.yearOfBirth]: person };
}, {});
console.log(peopleobject);
So how can I apply to the array of Objects reduce to get back what I am looking for? Please help, and thanks in advance.
<and>to do these comparisons. How can you modify your code to do this?Array#reduce? Unless it's academic, a simple for loop with a variable to keep track of max age found so far should do the job.