skip to Main Content

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


  1. 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:

    [1,2,3].reduce( 
        (accumulator, current) =>  accumulator + current,
        0
    );
    

    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.

    Login or Signup to reply.
  2. 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:

    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.

    Here are some examples of how to use reduce to solve various problems:

    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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search