Home >>JavaScript Array Reference >JavaScript Array reduce() Method

JavaScript Array reduce() Method

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 Values

Parameter Description
function(total,currentValue, index,arr) Itrequired to be run a function for each element in the array
Function arguments:
Argument Description
total It isRequiredand used to specify the initial value, or the previously returned value of the function
currentValue It requiredthe value for the current element
currentIndex It is used for the array index of the current element and it isOptional
arr It is used for the array object of the current element belongs to
initialValue It isOptional and a value to be passed to the function as the initial value

Browser Support

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>
Output:

 

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>					
Output:


Sum:

No Sidebar ads