By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – Can someone explain to me in the simplest of terms how the reduce method works exactly?
JavaScript

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

Admin
Last updated: 2023/12/23 at 6:19 AM
Admin
Share
5 Min Read
Can someone explain to me in the simplest of terms how the reduce method works exactly?

Problem:

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.

Contents
Problem:Solution:

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);

Expand snippet

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Vue - Eslint Complaining About Missing Variable in Setup Script Javascript – Vue – Eslint Complaining About Missing Variable in Setup Script
Next Article How to sort address in a table using javascript? Javascript – How to sort address in a table using javascript?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?