The JavaScript Array reduce() method executes a reducer function on each element of the array and returns a single output value.
Javascript array reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
The reduce() method reduces the given array into a single value by executing a reducer function. The user implements the reducer function that works on every element present in the array.
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Parameter: This method accepts five parameters as mentioned above and described below:
<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>