假设我们有一个对象数组,其中包含有关某些数据存储设备的信息,例如:
const drives = [ {size:"900GB", count:3}, {size:"900GB", count:100}, {size:"1200GB", count:5}, {size:"900GB", count:1} ];
请注意,相同大小的商品多次出现。
我们需要编写一个函数,该函数接受一个这样的数组,并将所有重复的大小合并为一个数组索引,并且显然将它们的计数相加。
const drives = [ {size:"900GB", count:3}, {size:"900GB", count:100}, {size:"1200GB", count:5}, {size:"900GB", count:1} ]; const groupDrives = (arr = []) => { const map = drives.reduce((map, e) => { if (e.size in map) map[e.size].count += e.count else map[e.size] = e return map; }, {}) const result = Object.keys(map).map(function (k) { return this[k] }, map); return result; } console.log(groupDrives(drives));
输出结果
控制台中的输出将是-
[ { size: '900GB', count: 104 }, { size: '1200GB', count: 5 } ]