Reputation: 3081
I have an array like this one:
[
{
cardId: "4908r920-2394930-3302-222",
power: 3
},
{
cardId: "4908r920-2394930-3302-222",
power: 10
},
{
cardId: "6666640-92011-3302-888",
power: 932
},
{
cardId: "4908r920-2394930-3302-222",
power: 5
},
{
cardId: "6666640-92011-3302-888",
power: 9
}
]
As you can see, in this array there are two different cards:
The card which id is "4908r920-2394930-3302-222" and the other one which id is "6666640-92011-3302-888"
These cards have a different power, but they are duplicated in the array by the field cardId.
I need to remove the lower power repeated cards, I mean, the final array has to be as follows:
[
{
cardId: "4908r920-2394930-3302-222",
power: 10
},
{
cardId: "6666640-92011-3302-888",
power: 932
}
]
Any ideas? I would appreciate if the solution was in +ES6.
Thank you.
Upvotes: 0
Views: 42
Reputation: 22320
simply that , with array reduce
const Arr1 =
[ { cardId: "4908r920-2394930-3302-222", power: 3 }
, { cardId: "4908r920-2394930-3302-222", power: 10 }
, { cardId: "6666640-92011-3302-888", power: 932 }
, { cardId: "4908r920-2394930-3302-222", power: 5 }
, { cardId: "6666640-92011-3302-888", power: 9 }
]
const Arr2 = Arr1.reduce((acc,{cardId,power})=>
{
let card = acc.find(x=>x.cardId===cardId)
if (!card) acc.push({cardId,power})
else if (card.power<power) card.power=power
return acc
},[])
console.log( Arr2 )
Upvotes: 1