1

I've been trying to filter this array to only show the first unique 0 index of an array within an array.

My array is already sorted by the 1 index.

let players =  [["Jim", "100"], ["Brett", "32"], ["Brett", "20"], ["Jim", "20"]]

I want my output to be players = [["Jim", "100"], ["Brett", "32"]]

So in other words, if item[0] == 'Jim' and it's already occurred within the array, remove all subsequent arrays with item[0] == 'Jim'.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Is this the solution to your question : [here] [here]: https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array – Govi-Boy Jul 30 '20 at 04:39
  • I found a lot of questions asking the same, but couldn't translate it to an array of arrays instead of an array of strings/integers. Thanks though. – Brett Thurston Jul 30 '20 at 11:01

3 Answers3

2

Try this out.

const players =  [["Jim", "100"], ["Brett", "32"], ["Brett", "20"], ["Jim", "20"]];

const result = players.filter((player, index) => players.findIndex(([name]) => player[0] === name) === index);

console.log(result)

Array.prototype.findIndex will search for matches from left to right and return index of the very first match. Array.prototype.filter is for removing all later found items by comparing the related indexes.

Lewis
  • 14,132
  • 12
  • 66
  • 87
2

Use a filter operation with a Set to keep track of previously found names.

let players =  [["Jim", "100"], ["Brett", "32"], ["Brett", "20"], ["Jim", "20"]]

const filtered = players.filter(function([ name ]) {
  return !this.has(name) && !!this.add(name)
}, new Set())
  
console.log(filtered)

Since finding things in Sets is O(1), this is much more efficient that searching the array for matching records every iteration.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Thanks! My array has the potential for a lot of unique arrays, so I will mark this as the solution, even though the previous ones meet the request, too. Very much appreciated. – Brett Thurston Jul 30 '20 at 11:00
2

You could use a lookup table with key of index-0 value

let players = [['Jim', '100'], ['Brett', '32'], ['Brett', '20'], ['Jim', '20']]

const res = players.reduce(
  (lookup, elem) =>
    lookup[elem[0]] ? lookup : { ...lookup, [elem[0]]: elem[1] },
  {}
)

console.log(Object.entries(res))
hgb123
  • 13,869
  • 3
  • 20
  • 38