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