以这个数组为例:
[{id: 0, weight: 200}
{id: 0, weight: 200}
{id: 1, weight: 75}
{id: 2, weight: 5}]
我需要得到它的结果:
[ {id:0, times:2},
{id:1, times:1},
{id:2, times:1}]
最佳答案
你可以将数组缩减为一个新的数组
var arr = [
{ id: 0, weight: 200 },
{ id: 0, weight: 200 },
{ id: 2, weight: 75 },
{ id: 9, weight: 5 }
];
var arr2 = arr.reduce( (a,b) => {
var i = a.findIndex( x => x.id === b.id);
return i === -1 ? a.push({ id : b.id, times : 1 }) : a[i].times++, a;
}, []);
console.log(arr2)
关于javascript - 如何将数组中的重复对象分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064107/