JavaScript Array reduce() Method
- Previous Page push()
- Next Page reduceRight()
- Go to the Previous Level JavaScript Array Reference Manual
Definition and Usage
reduce()
The method reduces the array to a single value.
reduce()
The method executes the provided function for each value of the array (from left to right).
The return value of the function is stored in the accumulator (result/total).
Note:No operation is performed on array elements without values reduce()
Method.
Note:reduce()
The method does not change the original array.
Example
Example 1
Subtract the numbers in the array from the beginning:
var numbers = [175, 50, 25]; document.getElementById("demo").innerHTML = numbers.reduce(myFunc); function myFunc(total, num) {}} return total - num; }
Example 2
Round all numbers in the array and display the total:
<button onclick="myFunction()">Try it</button> <p>Sum of numbers in array: <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>
Syntax
array.reduce(function(total, currentValue, currentIndex, arr) initialValue)
Parameter Values
Parameters | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
function(total, currentValue, index, arr) | Required. A function to be run for each element in the array.
Function Parameters:
|
||||||||||
initialValue | Optional. The value passed to the function as the initial value. |
Technical Details
Return Value: | Returns the cumulative result of the last call to the callback function. |
---|---|
JavaScript Version: | ECMAScript 5 |
Browser Support
The numbers in the table indicate the first browser version that fully supports this method.
All browsers fully support this method. reduce()
Method:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome 3 | IE 9 | Edge 12 | Firefox 3 | Safari 5 | Opera 10.5 |
June 2009 | September 2010 | July 2015 | January 2009 | June 2010 | March 2010 |
Related Pages
Tutorial:JavaScript Array
Tutorial:JavaScript Array Const
Tutorial:JavaScript Array Methods
Tutorial:JavaScript Array Sorting
Tutorial:JavaScript Array Iteration
Manual:Array.reduceRight() Method
- Previous Page push()
- Next Page reduceRight()
- Go to the Previous Level JavaScript Array Reference Manual