Javascript – Reduce Method

Javascript – Reduce Method

Here are some of the examples how you can use reduce in javascript.The reduce() method in JavaScript is used to iterate through an array and transform its elements into a single accumulated value Given the array objects below
 
JavaScript · Student lesson

One array. One running result.

Learn reduce() through salaries, house counts, house prices, and nested objects. Read the code, follow each visit, and check the output.
01

Meet the workers

workers is an array containing five objects. Each object describes one worker. The age and phone numbers are not used in these calculations.
Full starting data and first console output
const workers = [
  {
    "name": "John",
    "salary": 1000,
    "age": 30,
    "house": [
      "Banglo",
      1300000
    ],
    "phoneNumbers": [
      "0124594378",
      "0124594379"
    ],
    "credentials": {
      "username": "john_doe",
      "password": "secret123"
    }
  },
  {
    "name": "Jane",
    "salary": 1200,
    "age": 25,
    "house": [
      "Apartment",
      500000
    ],
    "phoneNumbers": [
      "0124594380",
      "0124594381"
    ],
    "credentials": {
      "username": "jane_doe",
      "password": "secret456"
    }
  },
  {
    "name": "Bob",
    "salary": 1100,
    "age": 35,
    "house": [
      "Apartment",
      800000
    ],
    "phoneNumbers": [
      "0124594382",
      "0124594383"
    ],
    "credentials": {
      "username": "bob_doe",
      "password": "secret789"
    }
  },
  {
    "name": "Alice",
    "salary": 1300,
    "age": 28,
    "house": [
      "Apartment",
      600000
    ],
    "phoneNumbers": [
      "0124594384",
      "0124594385"
    ],
    "credentials": {
      "username": "alice_doe",
      "password": "secret101"
    }
  },
  {
    "name": "Charlie",
    "salary": 900,
    "age": 32,
    "house": [
      "Banglo",
      1500000
    ],
    "phoneNumbers": [
      "0124594386",
      "0124594387"
    ],
    "credentials": {
      "username": "charlie_doe",
      "password": "secret202"
    }
  }
];

console.log(workers);
The first log displays this array of five worker objects. Your browser may display expandable objects instead of formatted text.
02

How reduce() works

Think of reduce as a running result. It visits each worker in order and carries the result into the next visit. The final result can be a number, an array, or an object.
const result = workers.reduce((sum, worker) => {
  return /* updated result */;
}, 0);
Part Meaning
workers The whole array.
worker The current object: John, then Jane, Bob, Alice, Charlie.
sum The accumulator: the result carried from the previous visit.
=> { … } The callback function that runs once per worker.
return Sends the accumulator value to the next visit.
0 The starting value for a numeric accumulator.
[] The starting value when collecting an array.
The parameter names are your choice. Your original (sum, workers) works, but (sum, worker) makes the current object easier to recognise. Always return an accumulator in every branch of these callbacks.
03

Add every salary

Add the current salary to the running total. The accumulator starts at 0.
const totalSalary = workers.reduce((sum, worker) => {
  return sum + worker.salary;
}, 0);

console.log(totalSalary);

Follow the accumulator

Worker Before Added After
John 0 1000 1000
Jane 1000 1200 2200
Bob 2200 1100 3300
Alice 3300 1300 4600
Charlie 4600 900 5500

Console output

5500
04

Add salaries greater than 1100

Only Jane (1200) and Alice (1300) pass the condition. Bob earns exactly 1100, so > 1100 excludes him. Use >= 1100 to include him. For a worker who fails the condition, return sum keeps the total unchanged.
const totalSalaryMoreThan1100 = workers.reduce((sum, worker) => {
  if (worker.salary > 1100) {
    console.log(worker.name);
    return sum + worker.salary;
  }
  return sum;
}, 0);

console.log(totalSalaryMoreThan1100);

Follow the accumulator

Worker Before Added After
John 0 0 0
Jane 0 1200 1200
Bob 1200 0 1200
Alice 1200 1300 2500
Charlie 2500 0 2500

Console output

Jane
Alice
2500
05

Count Banglo houses

Check the house type at position 0. Add 1 for each matching worker. John and Charlie each add one, giving two Banglo entries. === checks strict equality.
const totalBanglo = workers.reduce((sum, worker) => {
  if (worker.house[0] === 'Banglo') {
    console.log(worker.name);
    return sum + 1;
  }
  return sum;
}, 0);

console.log(totalBanglo);

Follow the accumulator

Worker Before Added After
John 0 1 1
Jane 1 0 1
Bob 1 0 1
Alice 1 0 1
Charlie 1 1 2

Console output

John
Charlie
2
06

Add Banglo house prices

After checking the type, add the price at position 1. sum += worker.house[1] means sum = sum + worker.house[1]. John adds 1,300,000 and Charlie adds 1,500,000.
const totalBangloPrice = workers.reduce((sum, worker) => {
  if (worker.house[0] === 'Banglo') {
    sum += worker.house[1];
    return sum;
  }
  return sum;
}, 0);

console.log(totalBangloPrice);

Follow the accumulator

Worker Before Added After
John 0 1300000 1300000
Jane 1300000 0 1300000
Bob 1300000 0 1300000
Alice 1300000 0 1300000
Charlie 1300000 1500000 2800000

Console output

2800000
07

Collect usernames and passwords

Here the accumulator starts as [], an empty array. Each visit creates a new object and uses push() to append it. return sum passes the same growing array to the next visit.
const credentials = workers.reduce((sum, worker) => {
  sum.push({
    username: worker.credentials.username,
    password: worker.credentials.password
  });
  return sum;
}, []);

console.log(credentials);
Visit Object appended Array length
John john_doe 1
Jane jane_doe 2
Bob bob_doe 3
Alice alice_doe 4
Charlie charlie_doe 5

Console output

[
  {
    "username": "john_doe",
    "password": "secret123"
  },
  {
    "username": "jane_doe",
    "password": "secret456"
  },
  {
    "username": "bob_doe",
    "password": "secret789"
  },
  {
    "username": "alice_doe",
    "password": "secret101"
  },
  {
    "username": "charlie_doe",
    "password": "secret202"
  }
]
Why return sum? push() changes the array, but returns its new length. Returning sum.push(...) would pass a number to the next visit instead of the array.

These passwords are demonstration data. In a real application, do not store or log plain-text passwords; password verification belongs on the server with password hashes.

08

What to remember

Goal Start with Update Final result
Add all salaries 0 sum + worker.salary 5500
Add salaries > 1100 0 Add salary only when condition passes 2500
Count Banglo entries 0 Add 1 when type matches 2
Add Banglo prices 0 Add house[1] when type matches 2800000
Collect credentials [] push object, then return array 5 objects
Reading console output: logs inside a callback appear during the visits. The log after reduce() appears after all five visits. Descriptive names help: this lesson changes totalSalarMoreThan100 to totalSalaryMoreThan1100, and totaBangloPrice to totalBangloPrice. The calculations remain the same.
Try it yourselfChange the condition to worker.salary >= 1100. What is the new total?
Show answer1200 + 1100 + 1300 = 3600.
   
Related Posts
Leave a Reply

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