Reduce Method


reduce: Reducing an array to a single value. Powerhouse method!

The reduce() method is a powerful tool in JavaScript for iterating over an array and accumulating its elements into a single output value. It executes a provided "reducer" callback function on each element of the array, passing in the return value from the calculation on the preceding element.


Example 1: Summing Numbers in an Array

const numbers = [1, 2, 3, 4, 5];

// The reducer function takes an accumulator and the current value.
const sum = numbers.reduce((accumulator, currentValue) => {
  // Add the current value to the accumulator.
  return accumulator + currentValue;
}, 0); // 0 is the initial value of the accumulator.

console.log(sum); // Output: 15

Explanation This code initializes the accumulator to 0. The reduce method then iterates through the numbers array, adding each currentValue to the accumulator, resulting in the total sum of the array.


Example 2: Flattening an Array of Arrays

const nestedArray = [[1, 2], [3, 4], [5, 6]];

// The initial value is an empty array.
const flattenedArray = nestedArray.reduce((accumulator, currentValue) => {
  // Concatenate the current inner array to the accumulator.
  return accumulator.concat(currentValue);
}, []);

console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]

Explanation Here, reduce starts with an empty array [] as the accumulator. For each sub-array (currentValue) in nestedArray, it gets concatenated to the accumulator, effectively flattening the structure.


Example 3: Counting Occurrences of Items

const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'apple'];

// The initial value is an empty object.
const fruitCount = fruits.reduce((accumulator, currentValue) => {
  // If the fruit is already a key in the accumulator, increment its value.
  accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
  return accumulator;
}, {});

console.log(fruitCount); // Output: { apple: 3, banana: 1, orange: 2 }

Explanation This example uses an empty object {} as the initial accumulator. As reduce iterates through the fruits array, it counts the occurrences of each fruit and stores the count in the accumulator object.


Example 4: Finding the Maximum Value

const scores = [88, 95, 72, 100, 91];

// The initial value is the first element of the array.
const maxScore = scores.reduce((accumulator, currentValue) => {
  // Return the larger of the accumulator or the current value.
  return Math.max(accumulator, currentValue);
});

console.log(maxScore); // Output: 100

Explanation In this case, reduce compares the accumulator with the currentValue in each iteration. Math.max ensures that the accumulator always holds the largest value encountered so far, ultimately finding the maximum score.


Example 5: Grouping Objects by a Property

const people = [
  { name: 'Alice', age: 21 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 21 },
];

// Group people by their age.
const groupedByAge = people.reduce((accumulator, currentValue) => {
  const age = currentValue.age;
  // If the age key doesn't exist, create it with an empty array.
  if (!accumulator[age]) {
    accumulator[age] = [];
  }
  // Push the current person into the array for their age.
  accumulator[age].push(currentValue);
  return accumulator;
}, {});

console.log(groupedByAge);
// Output:
// {
//   '21': [ { name: 'Alice', age: 21 }, { name: 'Charlie', age: 21 } ],
//   '25': [ { name: 'Bob', age: 25 } ]
// }

Explanation This demonstrates grouping an array of objects. The reduce method iterates over the people array and organizes them into a new object where the keys are the ages and the values are arrays of people of that age.


Example 6: Removing Duplicates from an Array

const duplicateNumbers = [1, 2, 1, 3, 4, 3, 5];

// Use an empty array as the initial value.
const uniqueNumbers = duplicateNumbers.reduce((accumulator, currentValue) => {
  // If the current value is not already in the accumulator, add it.
  if (!accumulator.includes(currentValue)) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]

Explanation This code efficiently filters out duplicate values. The reduce method builds up a new array (accumulator), only adding a currentValue if it's not already present.


Example 7: Chaining Array Methods with Reduce

const numbersToProcess = [1, 2, 3, 4, 5];

// Double each number, filter for values greater than 5, and then sum them.
const result = numbersToProcess
  .map(num => num * 2) // [2, 4, 6, 8, 10]
  .filter(num => num > 5) // [6, 8, 10]
  .reduce((accumulator, currentValue) => accumulator + currentValue, 0); // 24

console.log(result); // Output: 24

Explanation This final example showcases the power of chaining reduce with other array methods. The code first doubles each number using map, then filters out numbers not greater than 5 with filter, and finally, reduce sums the remaining values.