JavaScript reduce() method


The reduce() method in JavaScript is a powerful array method used to execute a provided callback function on each element of the array (from left to right) to reduce it to a single value. It is commonly used for accumulating or combining values.

Syntax:

let result = array.reduce(callback(accumulator, currentValue, index, array), initialValue)
  • callback: A function that is called for each element in the array. It can accept up to four parameters:

    • accumulator: The accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
    • currentValue: The current element being processed in the array.
    • index (optional): The index of the current element being processed.
    • array (optional): The array reduce() was called upon.
  • initialValue (optional): A value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used, and reduce() will start from the second element.

Return Value:

  • The final, single value that results from the reduction process. If the array is empty and no initial value is provided, a TypeError will be thrown.

Key Points:

  • Accumulates values: The reduce() method is typically used to accumulate values, such as summing numbers or combining arrays.
  • Can return any type: The result can be a number, string, object, array, etc., depending on the logic implemented in the callback.
  • Modifies the initial value: If an initialValue is provided, it will be used as the first accumulator; otherwise, the first element in the array will be used.

Example 1: Basic usage (Sum of numbers)

let numbers = [1, 2, 3, 4]; let sum = numbers.reduce(function(accumulator, currentValue) { return accumulator + currentValue; // Accumulate sum }, 0); // Initial value is 0 console.log(sum); // 10

Example 2: Using arrow function (Product of numbers)

let numbers = [1, 2, 3, 4]; let product = numbers.reduce((accumulator, currentValue) => { return accumulator * currentValue; // Accumulate product }, 1); // Initial value is 1 console.log(product); // 24

Example 3: Flattening an array

let arrays = [[1, 2], [3, 4], [5]]; let flattened = arrays.reduce((accumulator, currentValue) => { return accumulator.concat(currentValue); // Combine arrays }, []); console.log(flattened); // [1, 2, 3, 4, 5]

Example 4: Counting occurrences of values

let fruits = ['apple', 'banana', 'orange', 'banana', 'orange', 'banana']; let count = fruits.reduce((accumulator, fruit) => { accumulator[fruit] = (accumulator[fruit] || 0) + 1; // Count occurrences return accumulator; }, {}); console.log(count); // { apple: 1, banana: 3, orange: 2 }

Example 5: Using thisArg

let multiplier = { factor: 2 }; let numbers = [1, 2, 3]; let total = numbers.reduce(function(accumulator, currentValue) { return accumulator + currentValue * this.factor; // Accumulate using this.factor }, 0, multiplier); console.log(total); // 12 (1*2 + 2*2 + 3*2)

Summary:

  • The reduce() method is a versatile and powerful way to accumulate or combine values from an array into a single output.
  • It can be used for various purposes, including summing, multiplying, flattening arrays, or counting occurrences of values.
  • The method provides flexibility in defining how the accumulation occurs through the callback function and allows for initialization with an initialValue.