Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a duplicate array from inside a nested array?

Tags:

javascript

I would like to remove duplicated arrays from a 2D array.

For example I have this 2D array:

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

and I want to remove the duplicate to only have this:

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

I tried:

arr.filter((v, i, a) => a.indexOf(v) == i)

but this only works for primitive data types, not objects like arrays.

like image 900
Michael Nittolo Avatar asked Dec 06 '25 20:12

Michael Nittolo


1 Answers

You can use Set method. The Set object stores unique values of any type, and automatically removes duplicates.

First convert all the sub arrays into string which can be compared. Then add them to Set to remove duplicates. Then convert the Set of strings to array by using Array.from(). At last parse the JSON object.

let arr = [[-1,0,1],[-1,-1,2],[-1,0,1]];
let uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArr); // output: [[-1,0,1],[-1,-1,2]]
like image 66
Smit Gabani Avatar answered Dec 08 '25 10:12

Smit Gabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!