JavaScript reduce Method

What is the reduce Method?

The reduce method executes a reducer function on each element of the array, resulting in a single output value.

Syntax:

array.reduce(callback, initialValue)

Parameters:

  1. callback: A function that is called on each element of the array.

    • accumulator (required): The accumulated result from the previous callback execution.

    • currentValue (required): The current element being processed in the array.

    • currentIndex (optional): The index of the current element.

    • array (optional): The array on which reduce was called.

  2. initialValue: An optional initial value for the accumulator.


How Does It Work?

  1. Starts with the initialValue (if provided, otherwise it takes the first element of the array as the initial accumulator).

  2. Processes each element of the array using the callback function.

  3. Returns a single value after processing all elements.


Example: Sum of an Array

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0); // Initial value is 0

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

Explanation:

  • Initial value: 0

  • Iteration 1: 0 + 1 = 1

  • Iteration 2: 1 + 2 = 3

  • Iteration 3: 3 + 3 = 6

  • Iteration 4: 6 + 4 = 10

  • Iteration 5: 10 + 5 = 15


Example: Flattening an Array

If you have an array of arrays and want to make it one-dimensional:

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

const flatArray = nestedArray.reduce((accumulator, currentValue) => {
  return accumulator.concat(currentValue);
}, []);

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

Example: Counting Occurrences

If you want to count how many times each element appears in an array:

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

const fruitCount = fruits.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
  return accumulator;
}, {});

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

Key Points

  1. Powerful Tool: Use reduce when you need to calculate a single value (sum, average, object, etc.) from an array.

  2. Initial Value Matters: Always provide an initial value unless you're sure the array has at least one element.

  3. Immutable Operations: Avoid modifying the original array inside reduce.