Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to remove duplicate arrays inside array of arrays

Tags:

Input:

[[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]] 

The output I want:

[[-1,-1,2],[-1,0,1]] 

Any other ideas except this one?

Thanks

like image 278
BAE Avatar asked May 17 '17 03:05

BAE


People also ask

How do you remove duplicate array elements in JavaScript?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

How do you prevent duplicate arrays?

To prevent adding duplicates to an array:Use the Array. includes() method to check if the value is not present in the array. If the value is not present, add it to the array using the push() method. The array will not contain any duplicate values.


2 Answers

You won't really get around stringifying the arrays, as that's the simplest (and reasonably fast) way to compare them by value. So I'd go for

Array.from(new Set(input.map(JSON.stringify)), JSON.parse) 

See also Remove Duplicates from JavaScript Array for other approaches, though most of them will require two values to be comparable by ===.

like image 131
Bergi Avatar answered Oct 02 '22 18:10

Bergi


Magic

d.filter(( t={}, a=> !(t[a]=a in t) )); 

I assume your input data are in array d. Explanation here.

let d = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]];  var r = d.filter((t={},a=>!(t[a]=a in t)));  console.log(JSON.stringify(r));
like image 31
Kamil Kiełczewski Avatar answered Oct 02 '22 18:10

Kamil Kiełczewski