October 02, 2017

Use JSON.stringify for storing in Sets

Set can store different kinds of element, but specifically for storing Arrays, you will have to use JSON.stringify() to avoid duplication.

without stringify:

let set = new Set();
set.add([1]);
set.add([1]);

set.size; // => 2

with stringify:

set.add(JSON.stringify([1]));
set.add(JSON.stringify([1]));

set.size; // => 1

Also, whenever you want to pull the data back as Arrays, use JSON.parse with Array.prototype.map()

[...set] //=> '[1]'
[...set].map(JSON.parse) //=> [1]