I have the following array of objects in 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
. 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. 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:
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:
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]) );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.