1

I have an array of array.

m = [[-100,100], [-100,-100], [-100,-100], [-100,100]]

And I want to remove the duplicates. I tried

 aa = [...new Set(m)];

// and 

let chkdup = (arr, tar) => tar.every(v => arr.includes(v))`. 

But I can't remove the duplicates.

In Python, I can easily check this [-100,100] in m. But I don't know the function in JS. includes is not working for this case.

4 Answers 4

2

This happens because [-100, 100] != [-100, 100]. What you can do is convert the arrays into strings, and compare the strings instead, with JSON.stringify.

let m = [[-100,100], [-100,-100], [-100,-100], [-100,100]]
m = m.map(item => JSON.stringify(item).trim()) // Stringify everything (remove leading white space)
m = [...new Set(m)] // Convert to array getting rid of duplicates
m = m.map(item => JSON.parse(item)) // Parse it

Note that this is not very efficient (The interpreter has to convert into a string and parse the object again) but it is the simpliest solution. What it does is it checks if the JSON string of 2 Objects is equal an will not work with your own classes.

Sign up to request clarification or add additional context in comments.

Comments

1

The reason why new Set doesn't work well is because in JavaScript, arrays with the same values are not equal. Try: console.log([-100,100] == [-100,100]); will return false. Please refer to this post if you simply wants to compare between arrays.

A workaround is to convert subarrays into strings, and use Set to deduplicate:

const arr = [
  [-100, 100],
  [-100, -100],
  [-100, -100],
  [-100, 100]
];

const setArray = new Set(arr.map(x => JSON.stringify(x)));

const result = [...setArray].map(x => JSON.parse(x));

console.log(result);

Using lodash uniq is a simple alternative.

Comments

1

You can simply do this thing using javascript Set , map then parse the value. For more information Map with Set

 m = [[-100,100], [-100,-100], [-100,-100], [-100,100]];
 result = Array.from(new Set(m.map(JSON.stringify)), JSON.parse);
 console.log(t);

Comments

1

You can stringify your arrays using .map() with JSON.stringify(), and enter that into a set. Since you now have an array of strings, the set will remove the duplicates as it can check for equality correctly. You can then use Array.from with a mapping function of JSON.parse to convert it back into an array of arrays:

const m = [[-100,100], [-100,-100], [-100,-100], [-100,100]];
const res = Array.from(new Set(m.map(JSON.stringify)), JSON.parse);
console.log(res);

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.