Array reduceRight() Method - Javascript Array

Javascript examples for Array:reduceRight

Description

The reduceRight() method reduces the array to a single value by executing a function for each value of the array from right-to-left.

Syntax

array.reduceRight(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.
Argument Description
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

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 = [2, 45, 30, 100];//from  w ww.ja v a  2  s  .  com

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

</body>
</html>

Related Tutorials