Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Array.prototype.reduceRight()

BaselineWidely available

ThereduceRight() method ofArray instances applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

See alsoArray.prototype.reduce() for left-to-right.

Try it

const array1 = [  [0, 1],  [2, 3],  [4, 5],];const result = array1.reduceRight((accumulator, currentValue) =>  accumulator.concat(currentValue),);console.log(result);// Expected output: Array [4, 5, 2, 3, 0, 1]

Syntax

js
reduceRight(callbackFn)reduceRight(callbackFn, initialValue)

Parameters

callbackFn

A function to execute for each element in the array. Its return value becomes the value of theaccumulator parameter on the next invocation ofcallbackFn. For the last invocation, the return value becomes the return value ofreduceRight(). The function is called with the following arguments:

accumulator

The value resulting from the previous call tocallbackFn. On the first call, its value isinitialValue if the latter is specified; otherwise its value is the last element of the array.

currentValue

The value of the current element. On the first call, its value is the last element ifinitialValue is specified; otherwise its value is the second-to-last element.

currentIndex

The index position ofcurrentValue in the array. On the first call, its value isarray.length - 1 ifinitialValue is specified, otherwisearray.length - 2.

array

The arrayreduceRight() was called upon.

initialValueOptional

Value to use as accumulator to the first call of thecallbackFn. If no initial value is supplied, the last element in the array will be used and skipped. CallingreduceRight() on an empty array without an initial value creates aTypeError.

Return value

The value that results from the reduction.

Description

ThereduceRight() method is aniterative method. It runs a "reducer" callback function over all elements in the array, in descending-index order, and accumulates them into a single value. Read theiterative methods section for more information about how these methods work in general.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots insparse arrays.

Unlike otheriterative methods,reduceRight() does not accept athisArg argument.callbackFn is always called withundefined asthis, which gets substituted withglobalThis ifcallbackFn is non-strict.

ThereduceRight() method isgeneric. It only expects thethis value to have alength property and integer-keyed properties.

All caveats aboutreduce discussed inwhen to not use reduce() apply toreduceRight as well. Because JavaScript has no lazy evaluation semantics, there is no performance difference betweenreduce andreduceRight.

Examples

How reduceRight() works without an initial value

The call to the reduceRightcallbackFn would look something like this:

js
arr.reduceRight((accumulator, currentValue, index, array) => {  // …});

The first time the function is called, theaccumulator andcurrentValue can be one of two values. If aninitialValue was provided in the call toreduceRight, thenaccumulator will be equal toinitialValue andcurrentValue will be equal to the last value in the array. If noinitialValue was provided, thenaccumulator will be equal to the last value in the array andcurrentValue will be equal to the second-to-last value.

If the array is empty and noinitialValue was provided,TypeError would be thrown. If the array has only one element (regardless of position) and noinitialValue was provided, or ifinitialValue is provided but the array is empty, the solo value would be returned without callingcallbackFn.

Some example run-throughs of the function would look like this:

js
[0, 1, 2, 3, 4].reduceRight(  (accumulator, currentValue, index, array) => accumulator + currentValue,);

The callback would be invoked four times, with the arguments and return values in each call being as follows:

accumulatorcurrentValueindexReturn value
First call4337
Second call7229
Third call91110
Fourth call100010

Thearray parameter never changes through the process — it's always[0, 1, 2, 3, 4]. The value returned byreduceRight would be that of the last callback invocation (10).

How reduceRight() works with an initial value

Here we reduce the same array using the same algorithm, but with aninitialValue of10 passed as the second argument toreduceRight():

js
[0, 1, 2, 3, 4].reduceRight(  (accumulator, currentValue, index, array) => accumulator + currentValue,  10,);
accumulatorcurrentValueindexReturn value
First call104414
Second call143317
Third call172219
Fourth call191120
Fifth call200020

The value returned byreduceRight this time would be, of course,20.

Sum up all values within an array

js
const sum = [0, 1, 2, 3].reduceRight((a, b) => a + b);// sum is 6

Run a list of asynchronous functions with callbacks in series each passing their results to the next

js
const waterfall =  (...functions) =>  (callback, ...args) =>    functions.reduceRight(      (composition, fn) =>        (...results) =>          fn(composition, ...results),      callback,    )(...args);const randInt = (max) => Math.floor(Math.random() * max);const add5 = (callback, x) => {  setTimeout(callback, randInt(1000), x + 5);};const mul3 = (callback, x) => {  setTimeout(callback, randInt(1000), x * 3);};const sub2 = (callback, x) => {  setTimeout(callback, randInt(1000), x - 2);};const split = (callback, x) => {  setTimeout(callback, randInt(1000), x, x);};const add = (callback, x, y) => {  setTimeout(callback, randInt(1000), x + y);};const div4 = (callback, x) => {  setTimeout(callback, randInt(1000), x / 4);};const computation = waterfall(add5, mul3, sub2, split, add, div4);computation(console.log, 5); // Logs 14// same as:const computation2 = (input, callback) => {  const f6 = (x) => div4(callback, x);  const f5 = (x, y) => add(f6, x, y);  const f4 = (x) => split(f5, x);  const f3 = (x) => sub2(f4, x);  const f2 = (x) => mul3(f3, x);  add5(f2, input);};

Difference between reduce and reduceRight

js
const a = ["1", "2", "3", "4", "5"];const left = a.reduce((prev, cur) => prev + cur);const right = a.reduceRight((prev, cur) => prev + cur);console.log(left); // "12345"console.log(right); // "54321"

Defining composable functions

Function composition is a mechanism for combining functions, in which the output of each function is passed into the next one, and the output of the last function is the final result. In this example we usereduceRight() to implement function composition.

See alsoFunction composition on Wikipedia.

js
const compose =  (...args) =>  (value) =>    args.reduceRight((acc, fn) => fn(acc), value);// Increment passed numberconst inc = (n) => n + 1;// Doubles the passed valueconst double = (n) => n * 2;// using composition functionconsole.log(compose(double, inc)(2)); // 6// using composition functionconsole.log(compose(inc, double)(2)); // 5

Using reduceRight() with sparse arrays

reduceRight() skips missing elements in sparse arrays, but it does not skipundefined values.

js
console.log([1, 2, , 4].reduceRight((a, b) => a + b)); // 7console.log([1, 2, undefined, 4].reduceRight((a, b) => a + b)); // NaN

Calling reduceRight() on non-array objects

ThereduceRight() method reads thelength property ofthis and then accesses each property whose key is a nonnegative integer less thanlength.

js
const arrayLike = {  length: 3,  0: 2,  1: 3,  2: 4,  3: 99, // ignored by reduceRight() since length is 3};console.log(Array.prototype.reduceRight.call(arrayLike, (x, y) => x - y));// -1, which is 4 - 3 - 2

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.reduceright

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp