Javascript examples for Array:reduce
The reduce() method reduces the array to a single value by running the provided function for each value of the array.
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
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 |
currentValue | Required. The value of the current element |
currentIndex | Optional. The array index of the current element |
arr | Optional. The array object the current element belongs to |
initialValue | Optional. A value to be passed to the function as the initial 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:
<!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>