Kostis
Kostis

Reputation: 119

Removing duplicate sub-arrays

I have an array as such: [[1,3],[2,5],[1,3],[2,5]] and i would like to remove any duplicate sub-arrays. I tried using this code:

 uniqueArray = array.filter(function(item, pos) {
   return array.indexOf(item) == pos;   });

It still returns true for all the cases.

Which function can i use to get the desired result.

Upvotes: 3

Views: 2214

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

You can use Array#filter with an object that will store a hash for each iterated tuple:

var arr = [[1,3],[2,5],[1,3],[2,5]];

var result = arr.filter(function(t) {
  var key = t.join('-');
  return this[key] ? false : (this[key] = true);
}, Object.create(null));

console.log(result);

Upvotes: 3

Slai
Slai

Reputation: 22876

Not the most efficient method, but the sub-arrays can be used as object keys:

a = [[1,3],[2,5],[1,3],[2,5]]

o = a.reduce((r, v) => (r[v] = v, r), {})

console.log(JSON.stringify( Object.values(o) ))
console.log(JSON.stringify( o ))

Update: seems a bit faster with numeric keys :

let a = [[1,3],[2,5],[1,3],[2,5]], t, b, n = _ => performance.now(), 
v = Object.values, l = t => console.log(JSON.stringify(b), t) 

t = n(); b = v(a.reduce((r, v) => (r[v] = v, r), {}))                   ; l(n() - t)

t = n(); b = v(a.reduce((r, v) => (r[v[0] + 1 / v[1]] = v, r), {}))     ; l(n() - t)

t = n(); b = v(a.reduce((r, v) => (r[v[0] + 1 / v[1]] = v, r), new Map)); l(n() - t)

Upvotes: 3

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

Conver the 2D array into 1D array with stringified elements

Then put then into a Set to automatically filter out the repeating elements

Now convert the Set back to an array and map the array by JSON parsing each element to restore back the arrays.

Readable and no nested loops.

const arr = [[1,3],[2,5],[1,3],[2,5]];

const setArray = new Set(arr.map(x => JSON.stringify(x)))

const uniqArray = [...setArray].map(x => JSON.parse(x))

console.log(uniqArray)

Upvotes: 5

Related Questions