JavaScript reduce()Method
Example
Calculate the total sum of the array elements:
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
Output:
125
Try it Yourself »
Definition and Usage
The reduce() method receives a function as an accumulator. Each value in the array (from left to right) is reduced, and finally computed to a single value.
reduce() can be used as a higher-order function for function composition.
Note:reduce() does not execute the callback function for an empty array.
Browser Support
The numbers in the table indicate the first browser version number that supports the method.
| Method | |||||
|---|---|---|---|---|---|
| reduce() | Yes | 9.0 | 3.0 | 4 | 10.5 |
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameters
| Parameter | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| function(total,currentValue, index,arr) | Required. A function used to execute on each array element. Function parameters:
|
||||||||||
| initialValue | Optional. The initial value passed to the function |
Technical Details
| Return value: | Returns the calculation result |
|---|---|
| JavaScript Version: | ECMAScript 3 |
More Examples
Example
Calculate the total sum of the array elements after rounding:
<button onclick="myFunction()">Click me</button>
<p>Sum of array elements:<span id="demo"></span></p>
<script>
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
return total + Math.round(num);
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}
</script>
Try it Yourself »
Other Extensions
JavaScript Array Object