Javascript Array reduceRight()

Introduction

Javascript array reduceRight() method executes a reducer function on each element of the array from right to left.

It returns a single value.

arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Parameter
Optional
Meaning
callback





Not





Function to execute on each value in the array
It takes four arguments:
accumulator - the value returned in last invocation of the callback or initialValue
currentValue - the current element being processed
index - Optional, the index of the current element.
array - Optional, the array itself.
initialValue
Optional
Value to use as accumulator to the first call of the callback.

If initialValue is not supplied, the last element in the array is used and skipped.

The following table shows the value in each iteration.

[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
  return accumulator + currentValue;
});
iterationaccumulator current Value index return value
1 4 33 7
2 7 22 9
3 9 11 10
4 10 00 10

The value returned by reduceRight() is 10.

And if initialValue is 10:

[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
  return accumulator + currentValue;
}, 10);
Iterationaccumulator current Value index return value
110 44 14
2 14 33 17
3 17 2219
4 19 11 20
5 20 00 20

The value returned by reduceRight() is 20.

Subtract the numbers in the array, starting from the end:

var numbers = [175, 50, 25];
console.log(numbers.reduceRight(myFunc));

function myFunc(total, num) {
  return total - num;
}

Subtract the numbers, right-to-left, and display the sum:

var numbers = [2, 45, 30, 100];

function getSum(total, num) {
  return total - num;
}
console.log(numbers.reduceRight(getSum));

Sum up all values within an array

var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
  return a + b;//from  ww  w. ja  va 2s .  co m
});
console.log(sum);// sum is 6

Flatten an array of arrays

var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
    return a.concat(b);
}, []);//from  ww w . j a v  a2  s  .c  o m

console.log(flattened);// flattened is [4, 5, 2, 3, 0, 1]

Difference between reduce and reduceRight

var a = ['A', 'B', 'C', 'D', 'E']; 
var left  = a.reduce(function(prev, cur)      { return prev + cur; }); 
var right = a.reduceRight(function(prev, cur) { return prev + cur; }); 

console.log(left);  //w w  w.  j  a v a  2 s. c  o  m
console.log(right); 



PreviousNext

Related