javascript - 删除数组中的重复对象,保留具有最大属性值的对象

标签 javascript arrays duplicates

我有一个这样的数组:

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/

相关文章:

javascript - 使用变量数组调用函数

javascript - 将子类分配给父类类型的属性

javascript - 我可以让一个属性在 vue v-for 中只出现一次吗

JavaScript:返回最大数字

java - 避免在基于 struts2 的应用程序中服务器繁忙时提交多个表单

javascript - 为什么变量名在同一行声明两次?

javascript - 如何向具有子元素的 <li> 添加下拉箭头

c++创建具有数组作为成员的对象

MySQL 删除重复项比插入忽略更快?

javascript - 在 Javascript 中删除数组中的重复元素