Javascript数组reduce()

JavaScript Array reduce()方法在数组的每个元素上执行reducer 函数 ,并返回单个输出值。

reduce()方法的语法为:

arr.reduce(callback(accumulator, currentValue), initialValue)

在这里, arr是一个数组。


reduce()参数

reduce()方法采用:

  • callback-在每个数组元素上执行的函数 (如果未提供initialValue,则第一个元素除外)。它吸收了
    • 累加器 -累积回调的返回值。
    • currentValue-从数组传递的当前元素。
  • initialValue (可选)-将在第一次调用时传递给callback()值。如果未提供,则第一个元素在第一次调用时充当累加器 ,并且不会在其上执行callback()

注意:在没有initialValue的空数组上调用reduce()将抛出TypeError


从reduce()返回值
  • 返回缩小数组后得出的单个值。

注意事项

  • reduce()从左到右为每个值执行给定的函数 。
  • reduce()不会更改原始数组。
  • 提供initialValue几乎总是更安全。

示例1:数组的所有值的总和
const numbers = [1, 2, 3, 4, 5, 6];

function sum_reducer(accumulator, currentValue) {
  return accumulator + currentValue;
}

let sum = numbers.reduce(sum_reducer);
console.log(sum); // 21

// using arrow function
let summation = numbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue
);
console.log(summation); // 21

输出

21
21

示例2:减去数组中的数字
const numbers = [1800, 50, 300, 20, 100];

// subtract all numbers from first number
// since 1st element is called as accumulator rather than currentValue
// 1800 - 50 - 300 - 20 - 100
let difference = numbers.reduce(
  (accumulator, currentValue) => accumulator - currentValue
);
console.log(difference); // 1330

const expenses = [1800, 2000, 3000, 5000, 500];
const salary = 15000;

// function that subtracts all array elements from given number
// 15000 - 1800 - 2000 - 3000 - 5000 - 500
let remaining = expenses.reduce(
  (accumulator, currentValue) => accumulator - currentValue,
  salary
);
console.log(remaining); // 2700

输出

1330
2700

这个例子清楚地说明了传递initialValue和不传递initialValue之间的区别。


示例3:从数组中删除重复项
let ageGroup = [18, 21, 1, 1, 51, 18, 21, 5, 18, 7, 10];
let uniqueAgeGroup = ageGroup.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(uniqueAgeGroup); // [ 18, 21, 1, 51, 5, 7, 10 ]

输出

[
  18, 21,  1, 51,
   5,  7, 10
]

示例4:按属性分组对象
let people = [
  { name: "John", age: 21 },
  { name: "Oliver", age: 55 },
  { name: "Michael", age: 55 },
  { name: "Dwight", age: 19 },
  { name: "Oscar", age: 21 },
  { name: "Kevin", age: 55 },
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (accumulator, currentObject) {
    let key = currentObject[property];
    if (!accumulator[key]) {
      accumulator[key] = [];
    }
    accumulator[key].push(currentObject);
    return accumulator;
  }, {});
}

let groupedPeople = groupBy(people, "age");
console.log(groupedPeople);

输出

{
  '19': [ { name: 'Dwight', age: 19 } ],
  '21': [ { name: 'John', age: 21 }, { name: 'Oscar', age: 21 } ],
  '55': [
    { name: 'Oliver', age: 55 },
    { name: 'Michael', age: 55 },
    { name: 'Kevin', age: 55 }
  ]
}

推荐读物: JavaScript Array reduceRight()


总计 0 评论

发表评论

作为 登录 | 登出 »

联系电话

18321263196

交换链接

互相学习

服务咨询

我的微信