Array.reduceRight
reduceRight — Loops in reverse thru the array starting from the last element, and for each value the result of the last callback is made available.
Description
Array.reduceRight(function callback, [mixed first])
Parameters
Name |
Description |
Type |
Default |
Optional |
callback |
See callback below. |
function |
|
No |
first |
See first below. |
mixed |
|
Yes |
callback
The following parameters is passed to the callback.
- previous
The value of the current index.
- value
The value of the current index.
- index
The current index.
- array
The array.
first
The value of previous for the first iteration.
If not provided the first loop is skipped.
Return values
Returns a new array with the return value from the callback.
Examples
Example #1 – reduceRight example
var array = [2, 4, 8];
var result = array.reduceRight(function () {
console.log(this);
return true;
});
console.log(result); // true
console.log(array); // [2, 4, 8]
var arr = [2, 4, 8];
var result = arr.reduceRight(function (previous, value, index, array) {
console.log(previous, value, index, array);
return true;
});
console.log(result); // true
console.log(arr); // [2, 4, 8]
Passing in a custom object for this.
var array = [2, 4, 8];
var result = array.reduceRight(function () {
console.log(this);
return true;
}, document.location);
console.log(result); // true
console.log(array); // [2, 4, 8]
False for 4
var array = [2, 4, 8];
var result = array.reduceRight(function (value) {
if (value === 4) {
return false;
}
return true;
});
console.log(result); // true
console.log(array); // [2, 4, 8]
Return false for all.
var array = [2, 4, 8];
var result = array.reduceRight(function (value) {
console.log(value);
return false;
});
console.log(result); // false
console.log(array); // [2, 4, 8]
Return a new array with values doubled of the input.
var array = [1, 2, 3, 4, 5];
var result = array.reduceRight(function (previous, value) {
var sum = previous + value;
console.log(previous, value, sum);
return sum;
});
console.log(result); // 15
var array = [1, 2, 3, 4, 5];
var result = array.reduceRight(function (previous, value) {
var sum = previous + value;
console.log(previous, value, sum);
return sum;
}, 0);
console.log(result); // 15
var array = [1, 2, 3, 4, 5];
var result = array.reduceRight(function (previous, value) {
var sum = previous * value;
console.log(previous, value, sum);
return sum;
}, 10);
console.log(result); // 1200
External references