JavaScript Array reduce() Method


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.

Syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Parameter: This method accepts five parameters as mentioned above and described below:

  • function(total, currentValue, index, arr): It is the required parameter and used to run for each element of array. It contains four parameter which are listed below:
    • total: It is required parameter and used to specify the initialValue, or the previously returned value of the function.
    • currentValue: It is required parameter and used to specify the value of the current element.
    • currentIndex: It is optional parameter and used to specify the array index of the current element.
    • arr: It is optional parameter and used to specify the array object the current element belongs to.
  • initialValue: It is optional parameter and used to specify the value to be passed to the function as the initial value.

Example

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

Example -