| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | [Back] [Original] |
Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 7.
reduce() (reducer) , .
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
.
, .
arr.reduce(callback[, initialValue])
callback. .
accumulator . , initialValue initialValue .
currentValue.
currentIndex Optional . initialValue 0, 1 .
array Optionalreduce() .
initialValue Optionalcallback . . reduce() .
.
reduce() callback , :
accumulatorcurrentValuecurrentIndexarray accumulator currentValue . reduce() initialValue , accumulator initialValue currentValue . initialValue , accumulator currentValue .
:
initialValue , reduce() 1 . initialValue 0 .
initialValue TypeError . ( ) initialValue , initialValue callback .
initialValue , .
var maxCallback = (acc, cur) => Math.max(acc.x, cur.x);
var maxCallback2 = (max, cur) => Math.max(max, cur);
// initialValue reduce()
[{ x: 22 }, { x: 42 }].reduce(maxCallback); // 42
[{ x: 22 }].reduce(maxCallback); // { x: 22 }
[].reduce(maxCallback); // TypeError
// map/reduce -
[{ x: 22 }, { x: 42 }].map((el) => el.x).reduce(maxCallback2, -Infinity);
reduce() .
[0, 1, 2, 3, 4].reduce(
function (accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
},
);
4 . .
callback |
accumulator |
currentValue |
currentIndex |
array |
|
|---|---|---|---|---|---|
| 1 | 0 |
1 |
1 |
[0, 1, 2, 3, 4] |
1 |
| 2 | 1 |
2 |
2 |
[0, 1, 2, 3, 4] |
3 |
| 3 | 3 |
3 |
3 |
[0, 1, 2, 3, 4] |
6 |
| 4 | 6 |
4 |
4 |
[0, 1, 2, 3, 4] |
10 |
reduce() (10) .
[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr);
reduce() , :
[0, 1, 2, 3, 4].reduce(function (
accumulator,
currentValue,
currentIndex,
array,
) {
return accumulator + currentValue;
}, 10);
accumulator |
currentValue |
currentIndex |
array |
||
|---|---|---|---|---|---|
| 1 | 10 |
0 |
0 |
[0, 1, 2, 3, 4] |
10 |
| 2 | 10 |
1 |
1 |
[0, 1, 2, 3, 4] |
11 |
| 3 | 11 |
2 |
2 |
[0, 1, 2, 3, 4] |
13 |
| 4 | 13 |
3 |
3 |
[0, 1, 2, 3, 4] |
16 |
| 5 | 16 |
4 |
4 |
[0, 1, 2, 3, 4] |
20 |
reduce() 20.
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
// sum is 6
.
var total = [0, 1, 2, 3].reduce(
(accumulator, currentValue) => accumulator + currentValue,
0,
);
.
var initialValue = 0;
var sum = [{ x: 1 }, { x: 2 }, { x: 3 }].reduce(function (
accumulator,
currentValue,
) {
return accumulator + currentValue.x;
}, initialValue);
console.log(sum); // logs 6
(arrow function) :
var initialValue = 0;
var sum = [{ x: 1 }, { x: 2 }, { x: 3 }].reduce(
(accumulator, currentValue) => accumulator + currentValue.x,
initialValue,
);
console.log(sum); // logs 6
var flattened = [
[0, 1],
[2, 3],
[4, 5],
].reduce(function (accumulator, currentValue) {
return accumulator.concat(currentValue);
}, []);
// : [0, 1, 2, 3, 4, 5]
:
var flattened = [
[0, 1],
[2, 3],
[4, 5],
].reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
var names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
} else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
var people = [
{ name: "Alice", age: 21 },
{ name: "Max", age: 20 },
{ name: "Jane", age: 20 },
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
var groupedPeople = groupBy(people, "age");
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
// friends - an array of objects
// where object field "books" - list of favorite books
var 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 - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(
function (accumulator, currentValue) {
return [...accumulator, ...currentValue.books];
},
["Alphabet"],
);
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]
:
: Set Array.from() , let orderedArray = Array.from(new Set(myArray)); .
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce((accumulator, current) => {
const length = accumulator.length;
if (length === 0 || accumulator[length - 1] !== current) {
accumulator.push(current);
}
return accumulator;
}, []);
console.log(result); //[1,2,3,4,5]
/**
* Runs promises from array of functions that can return promises
* in chained manner
*
* @param {array} arr - promise arr
* @return {Object} promise object
*/
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input),
);
}
// promise function 1
function p1(a) {
return new Promise((resolve, reject) => {
resolve(a * 5);
});
}
// promise function 2
function p2(a) {
return new Promise((resolve, reject) => {
resolve(a * 2);
});
}
// function 3 - will be wrapped in a resolved promise by .then()
function f3(a) {
return a * 3;
}
// promise function 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
// Building-blocks to use for composition
const double = (x) => x + x;
const triple = (x) => 3 * x;
const quadruple = (x) => 4 * x;
// Function composition enabling pipe functionality
const pipe =
(...functions) =>
(input) =>
functions.reduce((acc, fn) => fn(acc), input);
// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);
// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240
reduce() map() if (!Array.prototype.mapUsingReduce) {
Array.prototype.mapUsingReduce = function (callback, thisArg) {
return this.reduce(function (mappedArray, currentValue, index, array) {
mappedArray[index] = callback.call(thisArg, currentValue, index, array);
return mappedArray;
}, []);
};
}
[1, 2, , 3].mapUsingReduce(
(currentValue, index, array) => currentValue + index + array.length,
); // [5, 7, , 10]
// ECMA-262 , 5(Edition), 15.4.4.21
// : http://es5.github.io/#x15.4.4.21
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, "reduce", {
value: function (callback /*, initialValue*/) {
if (this === null) {
throw new TypeError(
"Array.prototype.reduce " + "called on null or undefined",
);
}
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// Steps 3, 4, 5, 6, 7
var k = 0;
var value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in o)) {
k++;
}
// 3. If len is 0 and initialValue is not present,
// throw a TypeError exception.
if (k >= len) {
throw new TypeError(
"Reduce of empty array " + "with no initial value",
);
}
value = o[k++];
}
// 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// accumulator, kValue, k, O ).
if (k in o) {
value = callback(value, o[k], k, o);
}
// d. Increase k by 1.
k++;
}
// 9. Return accumulator.
return value;
},
});
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-array.prototype.reduce |
This page was last modified on 2026 7 15 by MDN contributors.
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/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()Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |