简要记录下自己对于JavaScriptreduce()函数的学习小结。

原始问题来源于How to sum an array for each ID and create new array in react,问题如下:

有一个数组

1
2
3
4
5
6
7
8
9
const data = [
  {"id": "One", "number": 100}, 
  {"id": "One", "number": 150}, 
  {"id": "One", "number": 200}, 
  {"id": "Two", "number": 50}, 
  {"id": "Two", "number": 100}, 
  {"id": "Three", "number": 10}, 
  {"id": "Three", "number": 90}
];

提问者希望基于idnumber进行累加,并输出一个新的数组:

1
2
3
4
5
[
  {"id": "One", "number": 450},
  {"id": "Two", "number": 150}, 
  {"id": "Three", "number": 100}, 
]

由于自己当时正在Stackoverflow上刷reputation,所以看到这个问题后,毫不犹豫的写下了自己的答案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let result = data.reduce((a, v) => {
  let obj = a.find(i => i.id == v.id);
  if (obj) {
      obj.number += v.number;
  } else {
      a.push({...v});
  }
  return a;
}, [])
console.log(result);
console.log("-------------------------------")

虽然我的手速比较快,但是最后被原提问者选中的答案如下

1
2
let result = data.reduce((acc, {id, number}) => ({...acc, [id]: {id, number: acc[id] ? acc[id].number + number: number}}), {});
console.log(Object.values(result));

该写法通过给reduce函数的输出结果设置为{}对象的方式避免了需要判断是是否为空,最后通过Object.values()将结果转化为数组,相对于我之前的多行代码,此种写法只需要2行即可实现目的,更简洁更优化,学习了!