Description
The reduce() method executes a function on every item in the array and collects the results from previous calls.
This method has the form:
Array.reduce(callback[, initialValue])
Parameter | Description |
---|---|
callback | (required) Specifies the function to execute on each value in the array The callback is invoked with four arguments: 1. previousValue - the value previously returned in the last invocation of the callback, or initialValue, if supplied, 2. currentValue - The current element in the array being processed, 3. index - the index of the current element being processed in the array, and 4. array - the array that was called upon |
initialValue | (optional) Specifies the object to use as the first argument to the first call of the callback |
Note: The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.
Examples
The following example shows the basic use of this method.
<script>
function sumFunction(previousValue, currentValue, index, array) {
return previousValue + currentValue;
}
var sum = [0, 1, 2, 3].reduce(sumFunction);
document.write("sum = " + sum);
</script>
This produces the following result:
Browser Support
Firefox | IE | Chrome | Opera | Safari |
---|---|---|---|---|
Version Information
This form was added in version: 1.8