-2

-bit of a noobie question, but I have an array that looks like this:

[["john",13],
["jack",12],
["judy",14],
["john",18]]

In the event there is a duplicate name, I would like to remove the element with the highest score, such that it looks like this:

[["john",13],
["jack",12],
["judy",14]]

Standard method of removing duplicates don't work in this case and I am just wondering if anyone knows how this could be done?

Thanks in advance,

2

1 Answer 1

1

You could use reduce method and Map to get unique values and then you can use spread syntax to get array of arrays.

const data = [["john",13], ["jack",12], ["judy",14], ["john",18]]

const result = data.reduce((r, [k, v]) => {
  if(!r.get(k) || v < r.get(k)) r.set(k, v)
  return r;
}, new Map)

console.log([...result])

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

1 Comment

.entries() is not really required. Just spreading a Map creates the 2D array of entries

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.