| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | [Back] [Original] |
Get to know MDN better
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
reduce(callbackFn)
reduce(callbackFn, initialValue)
callbackFn callbackFn accumulator reduce()
accumulator callbackFn initialValue array[0]
currentValue initialValue array[0] array[1]
currentIndexcurrentValue initialValue 0 1
arrayreduce()
initialValue accumulator
initialValue callbackFn currentValue
initialValue accumulator callbackFn 2 currentValue accumulator
TypeError initialValue
reduce() callbackFn callbackFn accumulator accumulator callbackFn reduce()
reduce() thisArg callbackFn undefined this callbackFn globalThis
reduce() JavaScript reduce() undefined reduce() for
1 initialValue initialValue callbackFn
initialValue reduce 0
initialValue reduce 1 1 0
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()
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() 2 10 initialValue
[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
const objects = [{ x: 1 }, { x: 2 }, { x: 3 }];
const sum = objects.reduce(
(accumulator, currentValue) => accumulator + currentValue.x,
0,
);
console.log(sum); // logs 6
pipe
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
// 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
const asyncPipe =
(...functions) =>
(initialValue) =>
functions.reduce(async (acc, fn) => fn(await acc), initialValue);
reduce() undefined
console.log([1, 2, , 4].reduce((a, b) => a + b)); // 7
console.log([1, 2, undefined, 4].reduce((a, b) => a + b)); // NaN
reduce() this length length
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() JavaScript reduce()
reduce() for...of
const val = array.reduce((acc, cur) => update(acc, cur), initialValue);
//
let val = initialValue;
for (const cur of array) {
val = update(val, cur);
}
reduce()
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
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));
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()
const flattened = array.reduce((acc, cur) => acc.concat(cur), []);
const flattened = array.flat();
const groups = array.reduce((acc, obj) => {
const key = obj.name;
const curGroup = acc[key] ?? [];
return { ...acc, [key]: [...curGroup, obj] };
}, {});
const groups = Object.groupBy(array, (obj) => obj.name);
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], []);
const allBooks = friends.flatMap((person) => person.books);
const uniqArray = array.reduce(
(acc, cur) => (acc.includes(cur) ? acc : [...acc, cur]),
[],
);
const uniqArray = Array.from(new Set(array));
//
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];
}, []);
const roots = array.flatMap((val) => {
if (val < 0) return [];
const root = Math.sqrt(val);
if (Number.isInteger(root)) return [root, root];
return [val];
});
find() findIndex() some() every()
const allEven = array.reduce((acc, cur) => acc && cur % 2 === 0, true);
const allEven = array.every((val) => val % 2 === 0);
reduce()
| ECMAScript 2027 LanguageSpecification # sec-array.prototype.reduce |
Arrayat()concat()copyWithin()entries()every()fill()filter()find()findIndex()findLast()findLastIndex()flat()flatMap()forEach()includes()indexOf()join()keys()lastIndexOf()map()pop()push()reduce()reduceRight()reverse()shift()slice()some()sort()splice()toLocaleString()toReversed()toSorted()toSpliced()toString()unshift()values()with()[Symbol.iterator]()Object/Function| Web Proxy Viewer | New URL | Original Page |