3

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.

1
  • 1
    Are you looking for a general method for varying array lengths in the second dimension or will they alway be the same length? Commented Jan 20, 2023 at 6:35

2 Answers 2

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

0

This should remove duplicates and retain the original order; that is, it will remove the duplicates in place. Of course, I didn't test every possible case and there may be a more clever way to accomplish the same.

let aOrig = [[-1,0,1],[-1,0,1],[-1,-1,2],[-1,-1,2],[-1,0,1],[2],[-1,0,1,1],[-1,0],[2]],
    a = new Array(),
    c = new Array()
    order = new Array();
aOrig.forEach( (v,i) => a.push([v.toString(),i]) );
a.sort((a,b) => a[0] < b[0] );
//a.forEach ( v => console.log(v[0].toString() + " : " + v[1]));
order.push(a[0][1]);
for (i=1, l=a.length; i < l; i++) {
  if ( a[i][0] != a[i-1][0] ) {
    order.push(a[i][1]);
  }
}
//console.log(order.toString());
order.sort().forEach( v => c.push( aOrig[v] ) );
console.log('---------');
c.forEach( v => console.log(v.toString()) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.