JavaScript Array reduceRight() Method
Example
Subtract the numbers in the array, starting from the end:
var numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduceRight(myFunc);
function myFunc(total, num) {
return total - num;
}
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The reduceRight() method reduces the array to a single value.
The reduceRight() method executes a provided function for each value of the array (from right-to-left).
The return value of the function is stored in an accumulator (result/total).
Note: reduceRight() does not execute the function for array elements without values.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
reduceRight() | Yes | 9.0 | 3.0 | 4 | 10.5 |
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. Function arguments:
|
||||||||||
initialValue | Optional. A value to be passed to the function as the initial value |
Technical Details
Return Value: | Returns the accumulated result from the last call of the callback function |
---|---|
JavaScript Version: | ECMAScript 5 |
More Examples
Example
Subtract the numbers, right-to-left, and display the sum:
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [2, 45, 30, 100];
function getSum(total, num) {
return total - num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}
</script>
Try it Yourself »
Related Pages
JavaScript Tutorial: JavaScript Arrays
JavaScript Tutorial: JavaScript Iteration
JavaScript Reference: JavaScript reduce() Method
❮ JavaScript Array Reference