JavaScript reduceRight()Method
Example
Calculate the sum of the array elements:
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);
}
Output result:
125
Try it Yourself »
Definition and Usage
The functionality of the reduceRight() methodreduce()is the same as that of reduce(). The difference is that reduceRight() accumulates array items from the end of the array forward.
Note:reduce() will not execute the callback function for an empty array.
Browser Support
The numbers in the table indicate the first browser version number that supports this method.
| Method | |||||
|---|---|---|---|---|---|
| reduceRight() | Yes | 9.0 | 3.0 | 4 | 10.5 |
Syntax
array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
Parameters
| Parameter | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| function(total,currentValue, index,arr) | Required. The function used to execute on each array element. Function parameters:
|
||||||||||
| initialValue | Optional. The initial value passed to the function. |
Technical Details
| Return value: | Returns the calculation result. |
|---|---|
| JavaScript Version: | ECMAScript 3 |
More Examples
Example
From right to left, subtract each array element:
<button onclick="myFunction()">Click me</button>
<p>Calculated value:<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 »
Other extensions
JavaScript Array Object