Answers for "reduce function snippets"

0

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>
Posted by: Guest on February-26-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language