I am doing an exercise from The Odin Project where I need to find the oldest person within an array of objects (consisting of people of different ages) by using the array.reduce method. I got it working by looking up the solution trying to code along. I spent days trying to wrap my head around how the reduce method works the way it does in this scenario, but I don’t get it.
From what I gather, a function is generally passed to the reduce method with two parameter that always represent 1) the accumulated value of the array and 2) the current element being iterated over. But in the code that I’m posting below, the parameters seem to work in a way where they’re used to compare different objects within the array.
My question is this: The parameter ‘oldest’ clearly represents the oldest person in the array. That is one person. One element. How does that work, when the that parameter is supposed to represent the accumulated value of the array and, thus, several elements added together?
What am I not getting?
const findTheOldest = function(array) {
// Use reduce method to reduce the array by comparing current age with previous age
return array.reduce((oldest, currentPerson) => {
// oldestAge gets the age of the oldest person's year of death and birth
const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath);
// currentAge gets the age of the current person's year of death and birth
const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath);
// return name if current age is older than the oldest age, else return current oldest age
return oldestAge < currentAge ? currentPerson : oldest;
});
};
const getAge = function(birth, death) {
if (!death) {
death = new Date().getFullYear(); // return current year using Date()
}
return death - birth; // else just return age using death minus birth
console.log(findTheOldest(people).name); // Ray
2
Answers
The first value is the value returned from the previous iteration.
When you are using
reduce
as an accumulator, then the value you return is the accumulated value and it is common to give it a name indicating that.For example:
In the case of the code in your question, the returned value is the older of the previous value and the current value so a different name is used.
The accumulator parameter doesn’t have to be an accumulation of anything. It can be whatever you want it to be. The sum of values, the highest value, the lowest value, an frequency counting object such as {red:2, blue:3, white:0}, or whatever makes sense in the particular use case.
The reduce function works as follows:
Here are some examples of how to use reduce to solve various problems: