JavaScript(JS) array method - reduce
The reduce()
method is a built-in JavaScript array method that executes a provided function on each element of an array, resulting in a single output value. The function takes two arguments: an accumulator and the current value. The reduce()
method returns the final value of the accumulator.
Here's an example of how to use the reduce()
method:
let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce(function(accumulator, currentValue) { return accumulator + currentValue; }); console.log(sum); // 15
In this example, we have an array numbers
containing the elements [1, 2, 3, 4, 5]
. We use the reduce()
method to calculate the sum of all the elements in the numbers
array.
The reduce()
method takes a function as an argument, which is executed on each element of the array. The function takes two arguments: an accumulator and the current value. In this example, we start with an accumulator value of 0
and add the current value of the array to it. The returned value becomes the new value of the accumulator for the next iteration.
After all the iterations are completed, the reduce()
method returns the final value of the accumulator, which is the sum of all the elements in the array. We store the final sum value in the variable sum
, and log it to the console.
Note that you can also provide an initial value for the accumulator as a second argument to the reduce()
method. If no initial value is provided, the first element of the array is used as the initial value of the accumulator, and the iteration starts from the second element.