const arr = [
{ id: 1, count: 2 },
{ id: 2, count: 1 },
{ id: 1, count: 3 },
{ id: 3, count: 4 },
{ id: 2, count: 2 }
];
const filteredArr = arr.reduce((accumulator, current) => {
const existingItem = accumulator.find(item => item.id === current.id);
if (existingItem) {
existingItem.count += current.count;
} else {
accumulator.push(current);
}
return accumulator;
}, []);
console.log(filteredArr);数组对象根据某个值过滤重复的数据,并累加某个值
最新推荐文章于 2025-11-24 03:12:01 发布
该代码段展示了如何利用JavaScript的Array.prototype.reduce方法来过滤并合并具有相同id的对象,将它们的count属性相加。最终生成的新数组中,每个对象的id是唯一的,且count是对应id的所有对象的count之和。
5万+

被折叠的 条评论
为什么被折叠?



