Skip to content
Advertisement

How to build a Set of unique Arrays?

I want to add many arrays to a Javascript set, and ensure that only unique arrays are added to the set. However, when I try adding the same array multiple times, it is always added instead of rejected. The .has() method always returns false as well. How do I fix this?

const mySet = new Set();
mySet.add([1, 2, 3]);
mySet.add([4, 5]);
mySet.add([1, 2, 3]);

console.log(mySet);                 
// Gives:  Set(3) { [ 1, 2, 3 ], [ 4, 5 ], [ 1, 2, 3 ] } 
// I want: Set(2) { [ 1, 2, 3 ], [ 4, 5 ] }

console.log(mySet.has([1, 2, 3]));  
// Gives:  false
// I want: true

Advertisement

Answer

I’d use a Map instead, indexed by the stringified version of the array:

const map = new Map();
const addToMap = arr => map.set(JSON.stringify(arr), arr);
addToMap([1, 2, 3]);
addToMap([4, 5]);
addToMap([1, 2, 3]);

console.log([...map.values()]);
Advertisement