-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,

HarryShotta
  • 347
  • 1
  • 15
  • 1
    Possible duplicate of [JavaScript: Remove duplicates of objects sharing same property value](https://stackoverflow.com/questions/32238602/javascript-remove-duplicates-of-objects-sharing-same-property-value) – Herohtar Oct 30 '19 at 21:17
  • Thanks. Found lots of useful information on here. – HarryShotta Oct 30 '19 at 21:23

1 Answers1

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])
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • 1
    `.entries()` is not really required. Just spreading a `Map` creates the 2D array of entries – adiga Oct 30 '19 at 21:31