JavaScript: Array.prototype.reduceRight
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)
returnsf(f(f(4,3),2),1)
.The function f is passed 4 args:
- The previousResult
- The currentValue
- The currentIndex
- 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