reduce function snippets
/* The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in
single output value.*/
// Round all the numbers in an array, and display the sum:
<button onclick="myFunction()">Get the Sum</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>