this function returns the oldest person and from what I understand the reduce function is about returning an accumulated value but I have been trying to understand this function for so long and I couldn't. where is the value to be accumulated
const people = [
{
name: "Carly",
yearOfBirth: 2018,
},
{
name: "Ray",
yearOfBirth: 1962,
yearOfDeath: 2011,
},
{
name: "Jane",
yearOfBirth: 1912,
yearOfDeath: 1941,
},
]
const findTheOldest = function(array) {
return array.reduce((oldest, currentPerson) => {
const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath);
const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath);
return oldestAge < currentAge ? currentPerson : oldest;
})
};
const getAge = function(birth, death) {
if (!death) {
death = new Date().getFullYear();
}
return death - birth;
};
module.exports = findTheOldest;
CodePudding user response:
So the accumulator here is the older person between the comparison of 2 people. What your code does is comparing 2 people, if one of them is the oldest, then it's compared to the next one, then you keep the oldest between them 2 and so on. At the end you just return the oldest. Instead of summing up things like you would normally do, you just return a value which is the older person so it's compared to the next one:
return oldestAge < currentAge ? currentPerson : oldest;
That line verifies which is the oldest between 2
if(current is older than previous)
return currentPerson;
else
return oldest; (which would be the previous value)
CodePudding user response:
The reduce function is commonly used to accumulate values, but that isn’t how it has to work.
You have a callback function which gets some arguments. The first two are:
- The value returned from the previous call to the callback function
- The current value from the array
When you run out of items in the array, the reduce
function returns the return value of the last call to the callback function.
In this case it gets two arguments which are named oldest
and currentPerson
.
oldest
is whatever is returned from the previous call to the function. So it is the “oldest person object that has been examined so far”.
currentPerson
is the one currently being looked at on the array.
It compares the age of the two people and returns whichever of them is the oldest one.
In the end, you get the oldest value from the whole array.
CodePudding user response:
It is true that the example function is written in a complicated way...
I rewrote it here in a more comprehensive way? (IMHO)
const
people =
[ { name: 'Carly', yearOfBirth: 2018 }
, { name: 'Ray', yearOfBirth: 1962, yearOfDeath: 2011 }
, { name: 'Jane', yearOfBirth: 1912, yearOfDeath: 1941 }
]
console.log( findTheOldest(people) )
function findTheOldest( arr )
{
const
cYear = new Date().getFullYear()
, getAge = pers => (pers.yearOfDeath || cYear) - pers.yearOfBirth
, callBackF = (oPers, cPers) => (getAge(oPers) > getAge(cPers)) ? oPers : cPers
;
return arr.reduce( callBackF )
}