Let's assume that we are working with the following 2-dimensional array and we want to remove duplicates:
javascript// [1,2] is a duplicated element let array = [[1, 2], [2, 3], [2, 2], [4, 5], [1, 2]];
If you try to create a unique set of elements:
javascriptlet unique = new Set(array); console.log(unique); // Set(5) {[1, 2], [2, 3], [2, 2], [4, 5], [1, 2]} // It doesn't work! We still have duplicates...
Using a Set(array)
object doesn't work in these cases. So, how we can do it?
javascript// Defining an empty Set let unique = new Set(); // Getting a no duplicates array let noDuplicates = array.filter(elem => { // Array to string. [1,2] -> "[1,2]" let string = JSON.stringify(elem); // Is already in the Set let isAlreadySeen = unique.has(string); // Adding element to Set won't create duplicates unique.add(string); // Return result return isAlreadySeen ? false : true; }); console.log(noDuplicates); // [[1, 2], [2, 3], [2, 2], [4, 5]]
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.