Home >>JavaScript Array Reference >JavaScript Array reduce() Method
JavaScript array reduced() methodis used to reduces the given array into a single value by executing a provided function and the return value of the function is stored in an accumulator. Therefore, it executes a provided function for each value of the array (from left to right).
Syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameter | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
function(total,currentValue, index,arr) | Itrequired to be run a function for each element in the array Function arguments:
|
||||||||||
initialValue | It isOptional and a value to be passed to the function as the initial value |
Method | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
reduce() | Yes | 9.0 | 3.0 | 4 | 10.5 |
Here is an Example of Array reduce() method:
<html> <body> <p id="reduce"></p> <script> var x = [400, 150, 45]; document.getElementById("reduce").innerHTML = x.reduce(myReduced); function myReduced(total, num) { return total - num; } </script> </body> </html>
Example 2:
<html> <head> <title> JavaScript Array reduce() Method </title> </head> <body> <button onclick="myphp()"> Click Here! </button> <br><br> Sum: <span id="Reduce1"></span> <script> var a = [1.85, 15.3, 18.3, 35.9]; function sumofArray(sum, num) { return sum + Math.round(num); } function myphp(item) { document.getElementById("Reduce1").innerHTML = a.reduce(sumofArray, 0); } </script> </body> </html>