| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | [Back] [Original] |
Get to know MDN better
reduce() reducer reducer
0 0 1 0
reduce()
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);
console.log(sumWithInitial);
// Expected output: 10
reducer
reduce(callbackFn)
reduce(callbackFn, initialValue)
callbackFn callbackFn accumulator reduce()
accumulator callbackFn initialValue array[0]
currentValue initialValue array[0] array[1]
currentIndexcurrentValue initialValue 0 1
array reduce()
initialValue accumulator initialValue callbackFn currentValue initialValue accumulator callbackFn currentValue accumulator
reducer
TypeError initialValue
reduce() reducercallbackFn accumulator accumulator callbackFn reduce()
reduce() thisArg callbackFn undefined this callbackFn globalThis
reduce() JavaScript reduce() undefined
reduce() callbackFn callbackFn
reduce() JavaScript reduce() reduce()
initialValue initialValue callbackFn
initialValue reduce 0
initialValue 1 1 0 reduce
const getMax = (a, b) => Math.max(a, b);
// 0
[1, 100].reduce(getMax, 50); // 100
[50].reduce(getMax, 10); // 50
// 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);
accumulator |
currentValue |
index |
||
|---|---|---|---|---|
15 |
16 |
1 |
31 |
|
31 |
17 |
2 |
48 |
|
48 |
18 |
3 |
66 |
|
66 |
19 |
4 |
85 |
array [15, 16, 17, 18, 19]reduce() 85
reduce 10 initialValue
[15, 16, 17, 18, 19].reduce(
(accumulator, currentValue) => accumulator + currentValue,
10,
);
accumulator |
currentValue |
index |
||
|---|---|---|---|---|
10 |
15 |
0 |
25 |
|
25 |
16 |
1 |
41 |
|
41 |
17 |
2 |
58 |
|
58 |
18 |
3 |
76 |
|
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); // 6
const flattened = [
[0, 1],
[2, 3],
[4, 5],
].reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
// flattened [0, 1, 2, 3, 4, 5]
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
const countedNames = names.reduce((allNames, name) => {
const currCount = allNames[name] ?? 0;
return {
...allNames,
[name]: currCount + 1,
};
}, {});
// countedNames
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
const people = [
{ name: "Alice", age: 21 },
{ name: "Max", age: 20 },
{ name: "Jane", age: 20 },
];
function groupBy(objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
const curGroup = acc[key] ?? [];
return { ...acc, [key]: [...curGroup, obj] };
}, {});
}
const groupedPeople = groupBy(people, "age");
console.log(groupedPeople);
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
// friendsbooks
const friends = [
{
name: "Anna",
books: ["Bible", "Harry Potter"],
age: 21,
},
{
name: "Bob",
books: ["War and peace", "Romeo and Juliet"],
age: 26,
},
{
name: "Alice",
books: ["The Lord of the Rings", "The Shining"],
age: 18,
},
];
// allbooks initialValue
const allbooks = friends.reduce(
(accumulator, currentValue) => [...accumulator, ...currentValue.books],
["Alphabet"],
);
console.log(allbooks);
// [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
Set Array.from() const arrayWithNoDuplicates = Array.from(new Set(myArray))
const myArray = ["a", "b", "a", "b", "c", "e", "e", "c", "d", "d", "d", "d"];
const myArrayWithNoDuplicates = myArray.reduce((accumulator, currentValue) => {
if (!accumulator.includes(currentValue)) {
return [...accumulator, currentValue];
}
return accumulator;
}, []);
console.log(myArrayWithNoDuplicates);
filter() map() reduce() for forEach()
const numbers = [-5, 6, 2, 0];
const doubledPositiveNumbers = numbers.reduce((accumulator, currentValue) => {
if (currentValue > 0) {
const doubled = currentValue * 2;
return [...accumulator, doubled];
}
return accumulator;
}, []);
console.log(doubledPositiveNumbers); // [12, 4]
/**
* Promise
*
* @param {array} arr Promise Promise
* @param {*} input Promise
* @return {Object} Promise Promise
*/
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input),
);
}
// Promise 1
function p1(a) {
return new Promise((resolve, reject) => {
resolve(a * 5);
});
}
// Promise 2
function p2(a) {
return new Promise((resolve, reject) => {
resolve(a * 2);
});
}
// 3 `.then()` Promise
function f3(a) {
return a * 3;
}
// Promise 4
function p4(a) {
return new Promise((resolve, reject) => {
resolve(a * 4);
});
}
const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10).then(console.log); // 1200
//
const double = (x) => 2 * x;
const triple = (x) => 3 * x;
const quadruple = (x) => 4 * x;
//
const pipe =
(...functions) =>
(initialValue) =>
functions.reduce((acc, fn) => fn(acc), initialValue);
//
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
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
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.reduce.call(arrayLike, (x, y) => x + y));
// 9
| ECMAScript 2027 LanguageSpecification # sec-array.prototype.reduce |
ArrayArray.prototype.at()Array.prototype.concat()Array.prototype.copyWithin()Array.prototype.entries()Array.prototype.every()Array.prototype.fill()Array.prototype.filter()Array.prototype.find()Array.prototype.findIndex()findLast()Array.prototype.findLastIndex()Array.prototype.flat()Array.prototype.flatMap()Array.prototype.forEach()Array.prototype.includes()Array.prototype.indexOf()Array.prototype.join()Array.prototype.keys()Array.prototype.lastIndexOf()Array.prototype.map()Array.prototype.pop()Array.prototype.push()Array.prototype.reduce()Array.prototype.reduceRight()Array.prototype.reverse()Array.prototype.shift()Array.prototype.slice()Array.prototype.some()Array.prototype.sort()Array.prototype.splice()Array.prototype.toLocaleString()Array.prototype.toReversed()Array.prototype.toSorted()Array.prototype.toSpliced()Array.prototype.toString()Array.prototype.unshift()Array.prototype.values()Array.prototype.with()Array.prototype[Symbol.iterator]()Object/FunctionObject.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()| Web Proxy Viewer | New URL | Original Page |