JavaScript - Arrays - reduceRight
// JavaScript - Array.prototype.reduceRight()
The reduceRight() method applies a function against an accumulator and each
value of the array (from right-to-left) has to reduce it to a single value.
arr.reduceRight(callback[, initialValue])
callback: Function to execute on each value in the array, taking four arguments:
1. previousValue: The value previously returned in the last invocation of the
callback, or initialValue, if supplied.
2. currentValue: The current element being processed in the array.
3. index: The index of the current element being processed in the array.
4. array: The array reduce was called upon.
initialValue: Optional. Object to use as the first argument to the first call
of the callback.
The reduceRight method returns the value that results from the reduction.
array.reduceRight(function(previousValue, currentValue, index, array) {
// ...
});
The first time the function is called, the previousValue and currentValue can be
one of two values. If an initialValue was provided in the call to reduceRight,
then previousValue will be equal to initialValue and currentValue will be equal
to the last value in the array. If no initialValue was provided, then
previousValue will be equal to the last value in the array and currentValue will
be equal to the second-to-last value.
If the array is empty and no initialValue was provided, TypeError would be
thrown. If the array has only one element (regardless of position) and no
initialValue was provided, or if initialValue is provided but the array is
empty, the solo value would be returned without calling callback.
var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
return a + b;
});
// sum is 6
There may be a difference between reduce and reduceRight depending on exactly
what you are doing in the accumulator function. For example, reduceRight can
be used to reverse an array.
page revision: 1, last edited: 14 Nov 2016 20:31