The JavaScript array reduce()
method is used to reduce the elements of an array to a single value. It executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total).
Syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameters:
function(total, currentValue, currentIndex, arr) – A function to execute on each element in the array.
Parameters of reducer’s function
total | Required. The initialValue, or the previously returned value of the function. |
currentValue | Required. The value of the current element. |
currentIndex | Optional. The index of the current element. |
arr | Optional. The array the current element belongs to. |
Example
var arr = [1, 2, 3, 4, 5];
var sum = arr.reduce(function(a, b) {
return a + b;
});
console.log(sum); // 15
Leave a Reply