How to reduce array to a value
Description
reduce()
is reduction method.
reduce()
iterates all items and build up a value for return.
reduce()
starts at the first item and traveling toward the last.
reduce()
accepts two arguments:
- a function to call on each item
- an optional initial value
The function passed into reduce() accepts four arguments:
- the previous value,
- the current value,
- the item's index,
- the array object.
The returned value from the function is passed in as the first argument for the next item. The first iteration occurs on the second item in the array.
Example
var values = [1,2,3,4,5];
// www .j av a2s .c om
var sum = values.reduce(function(prev, cur, index, array){
return prev + cur;
});
console.log(sum); //15
The code above generates the following result.