Brett Thurston
Brett Thurston

Reputation: 27

Remove an array, within an array by comparing the items' 0 index

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'.

Upvotes: 1

Views: 77

Answers (3)

Phil
Phil

Reputation: 164924

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.

Upvotes: 2

hgb123
hgb123

Reputation: 14891

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

Upvotes: 2

Lewis
Lewis

Reputation: 14916

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.

Upvotes: 2

Related Questions