How to use reduce method

The reduce() method executes a provided function for each array value (from left to right), resulting in a single output value.

The syntax of the reduce() method:

array.reduce((accumulator, currentValue, index, array) => { ... }, initialValue)
  • accumulator: the value returned from the previous iteration. It will be initialValue for the first iteration
  • currentValue: the value of the current element
  • index: the index of the current element (Optional)
  • arr: array object (Optional)
  • initialValue: A value to be passed to the function as the initial value (Optional)

I. Sum numbers

For example, we have an array of numbers, and we want to sum the numbers:

// Using for loop

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

let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(sum); // 15
// Using reduce

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

const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15

In the above example:

  • reduce() is a function with 2 parameters total (accumulator) and num (currentValue)
  • The reduce() function cycles through each value in the array just like in a for loop.
  • In this particular example, we want to add num to total.
  • The calculation is repeated continuously for each value in an array, but every time the num value changes to the next value in the array, it moves right.
  • When no more values exist in the array, the reduce() method returns the total value.
callback iterationaccumulatorcurrentValuereturn value
first call011
second call123
third call336
fourth call6410
fifth call10515

II. Flatten an array

Flattening an array is to convert an array of arrays into a single array that contains all values. We can do so with reduce() method.

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flatValues = data.reduce((total, value) => {
  return total.concat(value);
}, []);

console.log(flatValues); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

We can use the spread operator to make it shorter:

const data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

const flatValues = data.reduce(
  (total, value) => [...total, ...value], []
);

console.log(flatValues); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

III. Remove duplicate items in an array

We can use push() and indexOf() with reduce() function to remove duplicates from the array.

const data = [1, 2, 3, 1, 4, 3, 3, 5, 5, 5, 8, 9];
const order = data.reduce((accumulator, value) => {
  if (accumulator.indexOf(value) === -1) {
    accumulator.push(value);
  }
  return accumulator;
}, []);

console.log(order); // [1, 2, 3, 4, 5, 8, 9]

IV. Reduce an array into an object

For example, we have an order. We want to know the number of each dish in the order.

const order = ["chicken", "pizza", "burger", "pizza", "pizza", "chicken", "burger", "burger", "pasta"];

const order = dishes.reduce((total, dish) => {
  const dishCount = total[dish];
  dishCount ? (total[dish] = dishCount + 1) : (total[dish] = 1);
  return total;
}, {});

console.log(order)
// {chicken: 2, pizza: 3, burger: 3, pasta: 1}