Javascript's Reduce Method


Nov 22 2024

If you want to reduce an array to a single value. In this case, JavaScript's reduce method can help. It iterates over an array and accumulate its elements into a single value.

Syntax

Here is the syntax for the reduce() method:

array.reduce((accumulator, current, currentIndex, array)=>output, initialValue)
  • callback: A function that is executed on each array element. It takes four arguments:
    • accumulator: The accumulated value returned after each iteration.
    • currentValue: The current element being processed.
    • currentIndex (optional): The index of the current element.
    • array (optional): The array reduce is being called on.
  • initialValue (optional): A starting value for the accumulator. If not provided, the first array element is used as the initial value, and iteration starts from the second element.

Example

Suppose you have an array of numbers, and you want to find their sum using the reduce method. Here is how to achieve this.

const numbers = [1, 2, 7];

const result = numbers.reduce((acc, curr) => {
  console.log(acc, curr);

  /*
  
  Initial Value is zero so the first value of the acc is also zero.
  
  acc  curr
    0     1
    1     2
    3     7
  
  */

  return acc + curr;
}, 0);

console.log(result); // 10

As you can see above, The 0 is passed as the initialValue. This means the first value of acc will be 0.

Here, for each element in numbers, the callback function adds the current value curr to the accumulator acc, and this sum becomes the new acc for the next iteration.

This process continues for each element in the array until all elements have been processed. The final result is the accumulated sum of all the elements in the array.

Conclusion

The reduce() method in JavaScript is used to process an array and return a single cumulative value, such as a sum, product, or an object. In this article, we have discussed it by providing its syntax and example.

Thank you for reading.