删除数组中的重复对象,保留具有最大属性值的对象 [英] removing duplicate objects in an array, keeping ones with maximum property value

查看:29
本文介绍了删除数组中的重复对象,保留具有最大属性值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

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'

The order of the object does not matter as long as it can find the 'id' with the larger quantity

我尝试过 filter + findIndex、map +filter 等,但我一直在犯错误.我需要帮助.

I tried filter + findIndex, map +filter, etc but I kept making mistake. I need help.

推荐答案

您可以使用哈希表并检查结果集中是否存在具有相同 id 的对象.如果实际数量较大,则分配实际对象.

You could use a hash table and check if an object with the same id is in the result set. If the actual quantity is greater, assign the actual object.

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; }

这篇关于删除数组中的重复对象,保留具有最大属性值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆