1

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
Espresso
  • 740
  • 13
  • 32
  • Arrays are objects and are compared purely based on identity. – Pointy Jan 19 '21 at 16:20
  • 2
    `Set` is doing exactly what it is supposed to do. The first `[1, 2, 3]` is a different object than the second `[1, 2, 3]` you added. – Heretic Monkey Jan 19 '21 at 16:20
  • Does this answer your question? [Map/Set to maintain unique array of arrays, Javascript](https://stackoverflow.com/questions/43772320/map-set-to-maintain-unique-array-of-arrays-javascript) – Heretic Monkey Jan 19 '21 at 16:22

1 Answers1

2

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()]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320