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?
JavaScript
x
13
13
1
const mySet = new Set();
2
mySet.add([1, 2, 3]);
3
mySet.add([4, 5]);
4
mySet.add([1, 2, 3]);
5
6
console.log(mySet);
7
// Gives: Set(3) { [ 1, 2, 3 ], [ 4, 5 ], [ 1, 2, 3 ] }
8
// I want: Set(2) { [ 1, 2, 3 ], [ 4, 5 ] }
9
10
console.log(mySet.has([1, 2, 3]));
11
// Gives: false
12
// I want: true
13
Advertisement
Answer
I’d use a Map instead, indexed by the stringified version of the array:
JavaScript
1
7
1
const map = new Map();
2
const addToMap = arr => map.set(JSON.stringify(arr), arr);
3
addToMap([1, 2, 3]);
4
addToMap([4, 5]);
5
addToMap([1, 2, 3]);
6
7
console.log([map.values()]);