JavaScript:比较数组元素属性,如果相同,则合并
javascriptweb developmentfront end technologyobject oriented programming
假设我们有一个对象数组,其中包含有关某些数据存储设备的信息,例如 −
const drivers = [ {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 } ]