0

PROBLEM

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.

QUESTION

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.

1 Answer 1

1

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 )

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.