JS: Array.prototype.reduceRight

By Xah Lee. Date: . Last updated: .
xArray.reduceRight(f)

like Array.prototype.reduce, but start from right to left.

For example:

  • [1,2].reduce(f)f(2,1)
  • [1,2,3].reduce(f)f(f(3,2),1)
  • [1,2,3,4].reduce(f)f(f(f(4,3),2),1)
const xx = [1, 2, 3, 4];
const f = ((x, y) => `f(${x},${y})`);
console.log(xx.reduceRight(f) === "f(f(f(4,3),2),1)");
xArray.reduceRight(f, initValue)

Start with f(initValue, last_array_item)

const aa = ["1", "2", "3", "4"];

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

console.log(aa.reduceRight(ff, "5") === "54321");

JavaScript. Array Reduce, Fold

JavaScript. Map, Iteration, Reduce