[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh/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()

20157

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

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 currentValue accumulator

reducer

TypeError

initialValue

reduce() reducercallbackFn accumulator accumulator callbackFn reduce()

callbackFn

reduce() thisArg callbackFn undefined this callbackFn globalThis

reduce() JavaScript reduce() undefined

reduce() callbackFn callbackFn

  • reduce() callbackFn
  • callbackFn
  • callbackFn callbackFn

reduce() this length

reduce()

reduce() JavaScript reduce() reduce()

initialValue initialValue callbackFn

initialValue reduce 0

initialValue 1 1 0 reduce

js
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()

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

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

reduce 10 initialValue

js
[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

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

console.log(sum); // 6

js
const flattened = [
  [0, 1],
  [2, 3],
  [4, 5],
].reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
// flattened  [0, 1, 2, 3, 4, 5]

js
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 }

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

initialValue

js
// 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))

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

reduce() .filter().map()

filter() map() reduce() for forEach()

js
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

js
/**
 *  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

js
// 
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()

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

js
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


Web Proxy Viewer  |  New URL  |  Original Page