reduceRight()
reduceRight<
T,Accumulator>(collection,iteratee,accumulator):Accumulator
reduceRight<
T>(collection,iteratee):T|undefined
reduceRight<
T,Accumulator>(collection,iteratee,accumulator):Accumulator
reduceRight<
T>(collection,iteratee):T[keyofT] |undefined
This method is like reduce except that it iterates over elements of collection from right to left.
Use array.reduceRight() or Object.values().reverse().reduce() directly instead.
Type Parameters
T: T
The type of elements in the array.
Accumulator: Accumulator
The type of the accumulated value.
Parameters
Overload 1:
collection: T[]
The collection to iterate over.
iteratee: (accumulator, value, index, array) => Accumulator
The function invoked per iteration.
accumulator: Accumulator
The initial value.
Overload 2:
collection: T[]
The collection to iterate over.
iteratee: (accumulator, value, index, array) => T
The function invoked per iteration.
Overload 3:
collection: T
The collection to iterate over.
iteratee: (accumulator, value, key, object) => Accumulator
The function invoked per iteration.
accumulator: Accumulator
The initial value.
Overload 4:
collection: T
The collection to iterate over.
iteratee: (accumulator, value, key, object) => T[keyof T]
The function invoked per iteration.
Returns: Accumulator
The accumulated value.
See Also
- Array.reduceRight() - MDN
- Browser support - Can I Use
- Object.values() - MDN
- Browser support - Can I Use
Since
2.0.0
Also known as
reduceRight (Lodash, es-toolkit, Remeda, Ramda, Effect) · ❌ (Radashi, Modern Dash, Antfu)
Example
const numbers = [1, 2, 3, 4, 5];
// ❌ Deprecated approach
const rightSum = reduceRight(numbers, (acc, num) => acc + num, 0);
console.log(rightSum); // 15
// ✅ Recommended approach (for arrays)
const rightSumNative = numbers.reduceRight((acc, num) => acc + num, 0);
console.log(rightSumNative); // 15
// ✅ Recommended approach (for objects)
const obj = { a: 1, b: 2, c: 3 };
const rightSumObj = Object.values(obj).reverse().reduce((acc, num) => acc + num, 0);
console.log(rightSumObj); // 6
How it works?
Reduces collection from right to left.
Deprecated: Use array.reduceRight() directly.
Native Equivalent
// ❌ reduceRight(arr, fn, init)
// ✅ arr.reduceRight(fn, init)
Use Cases
Process from right to left 📌
Reduce array starting from the last element.
const chars = ["a", "b", "c"];
chars.reduceRight((acc, c) => acc + c, "");
// => "cba"
Build right-associative structure
Create structures where order matters right-to-left.
const ops = [1, 2, 3];
ops.reduceRight((acc, n) => ({ value: n, next: acc }), null);
// => { value: 1, next: { value: 2, next: { value: 3, next: null } } }
Compose functions right-to-left
Apply functions in reverse order.
const fns = [x => x + 1, x => x * 2, x => x - 3];
fns.reduceRight((val, fn) => fn(val), 10);
// => (10 - 3) * 2 + 1 = 15