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.
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.
Share Improve this question edited Nov 13, 2017 at 0:47 Aaqib 10.4k4 gold badges23 silver badges32 bronze badges asked Nov 13, 2017 at 0:01 KostisKostis 1191 silver badge12 bronze badges 2- You may want to review stackoverflow./questions/9229645/… – S. Walker Commented Nov 13, 2017 at 0:22
-
Will the arrays always be sorted the same way? Is
[1,3]
a duplicate of[3,1]
? – RobG Commented Nov 13, 2017 at 0:53
3 Answers
Reset to default 5Conver 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)
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)
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);