简体   繁体   English

如何根据对象值从数组中删除特定对象

[英]How can I remove a specific object from my array based on object values

I have the following array of objects in javascript. 我在javascript中有以下对象数组。

[{
     's': 'ETHBTC',
     'q': 123456
},
{
     's': 'XMLBTC',
     'q': 545454
},
{
     's': 'ETHBTC',
     'q': 123451
}]

I want to remove the duplicate objects based on condition that if all the objects have same value of the key s ,I want to keep the only one that has the highest value of key q . 我想根据以下条件删除重复的对象:如果所有对象都具有相同的键s值,我想保留唯一一个具有最高键值q In the above example, I would want to only keep 在上面的示例中,我只想保留

[{
     's': 'ETHBTC',
     'q': 123456
},
{
     's': 'XMLBTC',
     'q': 545454
}]

because it has highest value of key q for key s : ETHBTC and s : XMLBTC was missing so I pushed it into the array. 因为它对于键s : ETHBTCs : XMLBTC具有最高的键q值,所以我将其推入数组。 What can be the best approach for it? 最好的方法是什么?

I'd reduce into an object indexed by s , checking whether the current object at that index (if any) has a higher or lower q , and then getting the Object.values of the result to turn it back into an array: 我将reduce为一个由s索引的对象,检查该索引处的当前对象(如果有)是否具有较高或较低的q ,然后获取结果的Object.values将该值转换回数组:

 const input = [{ 's': 'ETHBTC', 'q': 123456 }, { 's': 'XMLBTC', 'q': 545454 }, { 's': 'ETHBTC', 'q': 123451 }]; console.log( Object.values( input.reduce((a, item) => { const { s, q } = item; if (!a[s] || a[s].q < q) a[s] = item; return a; }, {}) ) ); 

ES5 compatible solution: 与ES5兼容的解决方案:

 var input = [{ 's': 'ETHBTC', 'q': 123456 }, { 's': 'XMLBTC', 'q': 545454 }, { 's': 'ETHBTC', 'q': 123451 }]; var outputObj = input.reduce(function (a, item) { var s = item.s, q = item.q; if (!a[s] || a[s].q < q) a[s] = item; return a; }, {}); console.log( Object.keys(outputObj).map(key => outputObj[key]) ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM