Onjsdev

Share


Javascript array reduce method

Javascript Reduce Array Method


By onjsdev

Nov 25th, 2023

The JavaScript reduce array method is a higher-order function that iterates over an array and reduces it to a single value.

In this article we will discuss its syntax and usage with examples.

Syntax

Here is the syntax for the reduce() method:

array.reduce((accumulator,current)=>output, initialValue)

The reduce array method takes two parameters, one of which is a callback function and other is the initialValue.

On other hand the callback function also takes two parameters:

  • accumulator => previous output of the callback
  • current => current item in the array

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 sum = 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(sum); // 10

As you see above, the first value of the accumulator variable is 0 and the first current element is 1. The reduce() method iterates through the elements in the array and runs the callback function.

The callback function adds the accumulator and current element, resulting in a new accumulator value. 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 javascript reduce array method is a powerful method that provides a way to reduce an array of values down to a single value.

In this article, we have discussed it by providing its syntax and example.

Thank you for reading.