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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With