[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce [Back]  [Original]

Array.prototype.reduce() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Array.prototype.reduce()

Baseline

20157

reduce() Array

0 0 1

const array = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

console.log(sumWithInitial);
// : 10

js
reduce(callbackFn)
reduce(callbackFn, initialValue)

callbackFn

callbackFn accumulator reduce()

accumulator

callbackFn initialValue array[0]

currentValue

initialValue array[0] array[1]

currentIndex

currentValue initialValue 0 1

array

reduce()

initialValue

accumulator initialValue callbackFn currentValue initialValue accumulator callbackFn 2 currentValue accumulator

TypeError

initialValue

reduce() callbackFn callbackFn accumulator accumulator callbackFn reduce()

callbackFn

reduce() thisArg callbackFn undefined this callbackFn globalThis

reduce() JavaScript reduce() undefined reduce() for

reduce() this length

1 initialValue initialValue callbackFn

initialValue reduce 0

initialValue reduce 1 1 0

js
const getMax = (a, b) => Math.max(a, b);

//  0 
[1, 100].reduce(getMax, 50); // 100
[50].reduce(getMax, 10); // 50

//  1  1 
[1, 100].reduce(getMax); // 100

// 
[50].reduce(getMax); // 50
[].reduce(getMax, 1); // 1

[].reduce(getMax); // TypeError

reduce()

reduce()

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);

4

accumulator currentValue index
15 16 1 31
2 31 17 2 48
3 48 18 3 66
4 66 19 4 85

array [15, 16, 17, 18, 19] reduce() (85)

reduce()

reduce() 2 10 initialValue

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

5

accumulator currentValue index
10 15 0 25
2 25 16 1 41
3 41 17 2 58
4 58 18 3 76
5 76 19 4 95

reduce() 95

initialValue

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

console.log(sum); // logs 6

pipe

js
const pipe =
  (...functions) =>
  (initialValue) =>
    functions.reduce((acc, fn) => fn(acc), initialValue);

// 
const double = (x) => 2 * x;
const triple = (x) => 3 * x;
const quadruple = (x) => 4 * x;

// 
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);

// 
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240

js
//  fn(acc)  acc.then(fn) 
// initialValue 
const asyncPipe =
  (...functions) =>
  (initialValue) =>
    functions.reduce((acc, fn) => acc.then(fn), Promise.resolve(initialValue));

// 
const p1 = async (a) => a * 5;
const p2 = async (a) => a * 2;
// 
// 
const f3 = (a) => a * 3;
const p4 = async (a) => a * 4;

asyncPipe(p1, p2, f3, p4)(10).then(console.log); // 1200

asyncPipe async/await pipe

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

reduce()

reduce() undefined

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

reduce()

reduce() this length length

js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 99, // length  3  reduce() 
};
console.log(Array.prototype.reduce.call(arrayLike, (x, y) => x + y));
// 9

reduce()

reduce() JavaScript reduce()

reduce() for...of

js
const val = array.reduce((acc, cur) => update(acc, cur), initialValue);

// 
let val = initialValue;
for (const cur of array) {
  val = update(val, cur);
}

reduce()

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,
  };
}, {});

allNames N names O(N^2)

allNames allNames reduce() for

js
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
const countedNames = names.reduce((allNames, name) => {
  const currCount = allNames[name] ?? 0;
  allNames[name] = currCount + 1;
  // allNames  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;
}

2 Making Tanstack Table 1000x faster with a 1 line change

reduce() reduce()

  • flat()

    js
    const flattened = array.reduce((acc, cur) => acc.concat(cur), []);
    
    js
    const flattened = array.flat();
    
  • Object.groupBy()

    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);
    
  • flatMap()

    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);
    
  • Set Array.from()

    js
    const uniqArray = array.reduce(
      (acc, cur) => (acc.includes(cur) ? acc : [...acc, cur]),
      [],
    );
    
    js
    const uniqArray = Array.from(new Set(array));
    
  • flatMap()

    js
    // 
    const 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];
    });
    

    filter()

  • find() findIndex() some() every()

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

reduce()

ECMAScript 2027 LanguageSpecification
# sec-array.prototype.reduce


Web Proxy Viewer  |  New URL  |  Original Page