Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Array.prototype.reduce()

BaselineWidely available

Thereduce() method ofArray instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Try it

const array1 = [1, 2, 3, 4];// 0 + 1 + 2 + 3 + 4const initialValue = 0;const sumWithInitial = array1.reduce(  (accumulator, currentValue) => accumulator + currentValue,  initialValue,);console.log(sumWithInitial);// Expected output: 10

Syntax

js
reduce(callbackFn)reduce(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 ofreduce(). 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 isarray[0].

currentValue

The value of the current element. On the first call, its value isarray[0] ifinitialValue is specified; otherwise its value isarray[1].

currentIndex

The index position ofcurrentValue in the array. On the first call, its value is0 ifinitialValue is specified, otherwise1.

array

The arrayreduce() was called upon.

initialValueOptional

A value to whichaccumulator is initialized the first time the callback is called.IfinitialValue is specified,callbackFn starts executing with the first value in the array ascurrentValue.IfinitialValue isnot specified,accumulator is initialized to the first value in the array, andcallbackFn starts executing with the second value in the array ascurrentValue. In this case, if the array is empty (so that there's no first value to return asaccumulator), an error is thrown.

Return value

The value that results from running the "reducer" callback function to completion over the entire array.

Exceptions

TypeError

Thrown if the array contains no elements andinitialValue is not provided.

Description

Thereduce() method is aniterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value ofcallbackFn is passed intocallbackFn again on next invocation asaccumulator. The final value ofaccumulator (which is the value returned fromcallbackFn on the final iteration of the array) becomes the return value ofreduce(). 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,reduce() does not accept athisArg argument.callbackFn is always called withundefined asthis, which gets substituted withglobalThis ifcallbackFn is non-strict.

reduce() is a central concept infunctional programming, where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript'sreduce(): you should usespreading or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. However, note that copying the accumulator may in turn lead to increased memory usage and degraded performance — seeWhen to not use reduce() for more details. In such cases, to avoid bad performance and unreadable code, it's better to use afor loop instead.

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

Edge cases

If the array only has one element (regardless of position) and noinitialValue is provided, or ifinitialValue is provided but the array is empty, the solo value will be returnedwithout callingcallbackFn.

IfinitialValue is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0.

IfinitialValue is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example:

js
const getMax = (a, b) => Math.max(a, b);// callback is invoked for each element in the array starting at index 0[1, 100].reduce(getMax, 50); // 100[50].reduce(getMax, 10); // 50// callback is invoked once for element at index 1[1, 100].reduce(getMax); // 100// callback is not invoked[50].reduce(getMax); // 50[].reduce(getMax, 1); // 1[].reduce(getMax); // TypeError

Examples

How reduce() works without an initial value

The code below shows what happens if we callreduce() with an array and no initial value.

js
const array = [15, 16, 17, 18, 19];function reducer(accumulator, currentValue, index) {  const returns = accumulator + currentValue;  console.log(    `accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,  );  return returns;}array.reduce(reducer);

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

accumulatorcurrentValueindexReturn value
First call1516131
Second call3117248
Third call4818366
Fourth call6619485

Thearray parameter never changes through the process — it's always[15, 16, 17, 18, 19]. The value returned byreduce() would be that of the last callback invocation (85).

How reduce() works with an initial value

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

js
[15, 16, 17, 18, 19].reduce(  (accumulator, currentValue) => accumulator + currentValue,  10,);

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

accumulatorcurrentValueindexReturn value
First call1015025
Second call2516141
Third call4117258
Fourth call5818376
Fifth call7619495

The value returned byreduce() in this case would be95.

Sum of values in an object array

To sum up the values contained in an array of objects, youmust supplyaninitialValue, so that each item passes through your function.

js
const objects = [{ x: 1 }, { x: 2 }, { x: 3 }];const sum = objects.reduce(  (accumulator, currentValue) => accumulator + currentValue.x,  0,);console.log(sum); // 6

Function sequential piping

Thepipe function takes a sequence of functions and returns a new function. When the new function is called with an argument, the sequence of functions are called in order, which each one receiving the return value of the previous function.

js
const pipe =  (...functions) =>  (initialValue) =>    functions.reduce((acc, fn) => fn(acc), initialValue);// Building blocks to use for compositionconst double = (x) => 2 * x;const triple = (x) => 3 * x;const quadruple = (x) => 4 * x;// Composed functions for multiplication of specific valuesconst multiply6 = pipe(double, triple);const multiply9 = pipe(triple, triple);const multiply16 = pipe(quadruple, quadruple);const multiply24 = pipe(double, triple, quadruple);// Usagemultiply6(6); // 36multiply9(9); // 81multiply16(16); // 256multiply24(10); // 240

Running promises in sequence

Promise sequencing is essentially function piping demonstrated in the previous section, except done asynchronously.

js
// Compare this with pipe: fn(acc) is changed to acc.then(fn),// and initialValue is ensured to be a promiseconst asyncPipe =  (...functions) =>  (initialValue) =>    functions.reduce((acc, fn) => acc.then(fn), Promise.resolve(initialValue));// Building blocks to use for compositionconst p1 = async (a) => a * 5;const p2 = async (a) => a * 2;// The composed functions can also return non-promises, because the values are// all eventually wrapped in promisesconst f3 = (a) => a * 3;const p4 = async (a) => a * 4;asyncPipe(p1, p2, f3, p4)(10).then(console.log); // 1200

asyncPipe can also be implemented usingasync/await, which better demonstrates its similarity withpipe:

js
const asyncPipe =  (...functions) =>  (initialValue) =>    functions.reduce(async (acc, fn) => fn(await acc), initialValue);

Using reduce() with sparse arrays

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

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

Calling reduce() on non-array objects

Thereduce() 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 reduce() since length is 3};console.log(Array.prototype.reduce.call(arrayLike, (x, y) => x + y));// 9

When to not use reduce()

Multipurpose higher-order functions likereduce() can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of usingreduce().

Note thatreduce() is always equivalent to afor...of loop, except that instead of mutating a variable in the upper scope, we now return the new value for each iteration:

js
const val = array.reduce((acc, cur) => update(acc, cur), initialValue);// Is equivalent to:let val = initialValue;for (const cur of array) {  val = update(val, cur);}

As previously stated, the reason why people may want to usereduce() is to mimic functional programming practices of immutable data. Therefore, developers who uphold the immutability of the accumulator often copy the entire accumulator for each iteration, like this:

js
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];const countedNames = names.reduce((allNames, name) => {  const currCount = Object.hasOwn(allNames, name) ? allNames[name] : 0;  return {    ...allNames,    [name]: currCount + 1,  };}, {});

This code is ill-performing, because each iteration has to copy the entireallNames object, which could be big, depending how many unique names there are. This code has worst-caseO(N^2) performance, whereN is the length ofnames.

A better alternative is tomutate theallNames object on each iteration. However, ifallNames gets mutated anyway, you may want to convert thereduce() to afor loop instead, which is much clearer:

js
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];const countedNames = names.reduce((allNames, name) => {  const currCount = allNames[name] ?? 0;  allNames[name] = currCount + 1;  // return allNames, otherwise the next iteration receives undefined  return allNames;}, Object.create(null));
js
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];const countedNames = Object.create(null);for (const name of names) {  const currCount = countedNames[name] ?? 0;  countedNames[name] = currCount + 1;}

Therefore, if your accumulator is an array or an object and you are copying the array or object on each iteration, you may accidentally introduce quadratic complexity into your code, causing performance to quickly degrade on large data. This has happened in real-world code — see for exampleMaking Tanstack Table 1000x faster with a 1 line change.

Some of the acceptable use cases ofreduce() are given above (most notably, summing an array, promise sequencing, and function piping). There are other cases where better alternatives thanreduce() exist.

  • Flattening an array of arrays. Useflat() instead.

    js
    const flattened = array.reduce((acc, cur) => acc.concat(cur), []);
    js
    const flattened = array.flat();
  • Grouping objects by a property. UseObject.groupBy() instead.

    js
    const groups = array.reduce((acc, obj) => {  const key = obj.name;  const curGroup = acc[key] ?? [];  return { ...acc, [key]: [...curGroup, obj] };}, {});
    js
    const groups = Object.groupBy(array, (obj) => obj.name);
  • Concatenating arrays contained in an array of objects. UseflatMap() instead.

    js
    const friends = [  { name: "Anna", books: ["Bible", "Harry Potter"] },  { name: "Bob", books: ["War and peace", "Romeo and Juliet"] },  { name: "Alice", books: ["The Lord of the Rings", "The Shining"] },];const allBooks = friends.reduce((acc, cur) => [...acc, ...cur.books], []);
    js
    const allBooks = friends.flatMap((person) => person.books);
  • Removing duplicate items in an array. UseSet andArray.from() instead.

    js
    const uniqArray = array.reduce(  (acc, cur) => (acc.includes(cur) ? acc : [...acc, cur]),  [],);
    js
    const uniqArray = Array.from(new Set(array));
  • Eliminating or adding elements in an array. UseflatMap() instead.

    js
    // Takes an array of numbers and splits perfect squares into its square rootsconst roots = array.reduce((acc, cur) => {  if (cur < 0) return acc;  const root = Math.sqrt(cur);  if (Number.isInteger(root)) return [...acc, root, root];  return [...acc, cur];}, []);
    js
    const roots = array.flatMap((val) => {  if (val < 0) return [];  const root = Math.sqrt(val);  if (Number.isInteger(root)) return [root, root];  return [val];});

    If you are only eliminating elements from an array, you also can usefilter().

  • Searching for elements or testing if elements satisfy a condition. Usefind() andfindIndex(), orsome() andevery() instead. These methods have the additional benefit that they return as soon as the result is certain, without iterating the entire array.

    js
    const allEven = array.reduce((acc, cur) => acc && cur % 2 === 0, true);
    js
    const allEven = array.every((val) => val % 2 === 0);

In cases wherereduce() is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks.

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp