我有一个这样的数组:
const array=[ {id:0, quantity:1}, {id:1, quantity:2}, {id:0, quantity:4} ]
我的目标是:
const array=[ {id:1, quantity:2}, {id:0, quantity:4} ]
对象的顺序无所谓,只要能找到数量较大的'id'即可
我尝试了 filter + findIndex、map +filter 等,但我总是出错。我需要帮助。
最佳答案
您可以使用哈希表并检查结果集中是否有具有相同 id
的对象。如果实际数量较大,则分配实际对象。
var array = [{ id: 0, quantity: 1 }, { id: 1, quantity: 2 }, { id: 0, quantity: 4 }],
hash = Object.create(null),
unique = array.reduce(function (r, o) {
if (!(o.id in hash)) {
hash[o.id] = r.push(o) - 1;
return r;
}
if (o.quantity > r[hash[o.id]].quantity) {
r[hash[o.id]] = o;
}
return r;
}, []);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 删除数组中的重复对象,保留具有最大属性值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45310384/