Search code examples
javascriptarraysmethods

Can someone explain to me in the simplest of terms how the reduce method works exactly?


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

Solution

  • 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, a frequency counting object such as {red:2, blue:3, white:0}, or whatever makes sense in a particular use case.

    The reduce function works as follows:

    reduce executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

    Note that if you don't provide an initial accumulator value then JavaScript simply uses the array element at index 0 as the initial accumulator value and the array iteration starts at the 2nd element in the array.

    Here are some examples of how to use reduce to solve various problems. The first is your typical, classic reduce scenario to sum a property (salary). The 2nd and 3rd are common min/max examples. The final one is a bit more sophisticated and it groups values by some property (an employee's team).

    const employees = [
      { name: "joe", age: 23, salary: 12000, team: "sales" },
      { name: "mary", age: 41, salary: 15000, team: "hr" },
      { name: "bob", age: 37, salary: 13000, team: "eng" },
      { name: "alice", age: 21, salary: 11000, team: "eng" },
    ];
    
    // What is the total payroll (initial accumulated value 0)?
    const payroll = employees.reduce((total, current) => {
      return total + current.salary;
    }, 0);
    
    // Which is the youngest employee (no initial value)?
    const youngest_employee = employees.reduce((youngest, current) => {
      return youngest.age < current.age ? youngest : current;
    });
    
    // Which is the highest paid employee (no initial value)?
    const highest_paid_employee = employees.reduce((highest, current) => {
      return highest.salary > current.salary ? highest : current;
    });
    
    // Which employees work for each team (initial value is object with
    // key/value pairs of team names to empty array of employee names)?
    const team_employee_names = employees.reduce(
      (accumulator, current) => {
        accumulator[current.team].push(current.name);
        return accumulator;
      },
      { sales: [], hr: [], eng: [] }
    );
    
    console.log("Payroll:", payroll);
    console.log("Youngest:", youngest_employee.name);
    console.log("Highest paid:", highest_paid_employee.name);
    console.log("Employee names by team:", team_employee_names);