JavaScript Array reduce()
Example
Subtract the numbers in the array, starting from the beginning:
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The reduce() method executes a reducer function for each value of an array.
reduce() returns a single value which is the function's accumulated result.
reduce() does not execute the function for empty array elements.
reduce() does not change the original array.
Browser Support
reduce() is fully supported in all modern browsers:
| Chrome 3 | IE 9 | Edge 12 | Firefox 3 | Safari 5 | Opera 10.5 |
| Jun 2009 | Sep 2010 | Jul 2015 | Jan 2009 | Jun 2010 | Mar 2010 |
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameter Values
| Parameter | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| function(total,currentValue, index,arr) | Required. A function to be run for each element in the array. Function arguments:
|
||||||||||
| initialValue | Optional. A value to be passed to the function as the initial value |
Technical Details
| Return Value: | Returns the accumulated result from the last call of the callback function |
|---|---|
| JavaScript Version: | ECMAScript 5 |
More Examples
Example
Round all the numbers in an array, and display the sum:
const numbers = [15.5, 2.3, 1.1, 4.7];
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
function getSum(total, num) {
return total + Math.round(num);
}
Try it Yourself »

