我的数组中有很多对象。我想获取具有相同“id”的任何对象,并将“num”值与同一“id”的其他“num”值进行比较。我希望将整个对象数组减少为每个 id 仅有最大数量的对象数组。这些可以重复,但任何小于最高编号的对象都应删除。所有其他键/值对也应该在创建的任何最终对象数组中一起出现。
{
random : ajabl,
num : 5, // should stay, highest number is 5
id :10
}
{
random: jlsl,
num : 4, // should go, highest number is 5
id : 10
}
{
random: jlssssl,
num : 5, // should stay, highest number is 5
id : 10
}
{
random: abcd,
num : 1, // should go, highest number is 5
id : 10
}
{
random : xy45,
num : 2, // Should stay, highest number is 2
id : 11
}
最佳答案
我认为你可以通过以下方式使用ES6来实现它:
let arr = [{
num : 5, // should stay, highest number is 5
id :10
},
{
num : 4, // should go, highest number is 5
id : 10
},
{
num : 5, // should stay, highest number is 5
id : 10
},
{
num : 1, // should go, highest number is 5
id : 10
},
{
num : 2, // Should stay, highest number is 2
id : 11
}];
let ids = Array.from(new Set(arr.map(i => i.id)));
let result = [];
Array.from(new Set(arr.map(i => i.id))).forEach(a => {
let tmp = arr.filter(i => i.id === a).sort((a,b) => b.num - a.num);
tmp.filter(i => i.num === tmp[0].num).map(j => result.push(j));
});
console.log(result);
Set运算符用于删除重复项。
首先将 ids 放入数组中,然后循环获取每个数组的每组对象,最后通过添加结果数组来将它们合并起来
关于javascript - 通过比较共享 value2 的元素的 value1 从数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59743117/