Array reduce() Method - Javascript Array

Javascript examples for Array:reduce

Description

The reduce() method reduces the array to a single value by running the provided function for each value of the array.

Syntax

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

Parameter Values

Parameter Description
function(total,currentValue, index,arr) Required. A function to be run for each element in the array.
total Required. The initialValue, or the previously returned value of the function
currentValueRequired. The value of the current element
currentIndexOptional. The array index of the current element
arr Optional. The array object the current element belongs to
initialValueOptional. A value to be passed to the function as the initial value

Return Value:

Returns the accumulated result from the last call of the callback function

The following code shows how to Get the sum of the numbers in the array:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>


<button onclick="myFunction()">Test</button>

<span id="demo"></span>

<script>
var numbers = [12, 45, 30, 100];//  ww  w .  j  av  a 2 s.c o  m

function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}
</script>

</body>
</html>

Related Tutorials