JavaScript: Array.prototype.reduceRight

By Xah Lee. Date: . Last updated: .
arrayX.reduceRight(f)
First computes f(x,y) where x is last item in array and y is second item from right, then apply f, taking a new array element from right as second argument, repeat, until all items in array are used, return result. For example, [1,2,3,4].reduceRight(f) returns f(f(f(4,3),2),1).

The function f is passed 4 args:

  1. The previousResult
  2. The currentValue
  3. The currentIndex
  4. The object being traversed.

The function f should return 1 value.

If array is empty, it's an error. Give initValue to avoid error.

arrayX.reduceRight(f, initValue)
Start with f(initValue, last_array_item) .
// example of reduceRight

const aa = ["a", "b", "c", "d"];

// a function that join 2 strings
const ff = function (x, y) {
    console.log( x, y );
    return x + y; }

console.log(
 aa.reduceRight(ff)
); // dcba


// prints

// d c
// dc b
// dcb a
// dcba

Example with given second argument.

// example of reduceRight

const aa = ["a", "b", "c", "d"];

// a function that join 2 strings
const ff = function (x, y) {
    console.log( x, y );
    return x + y; }

console.log(
 aa.reduceRight (ff, "3")
);

// prints

// 3 d
// 3d c
// 3dc b
// 3dcb a
// 3dcba

Reduce Left

Array.prototype.reduce

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Array

prototype