create a set in ES6 by passing an array into the constructor
let set = new Set([1, 2, 3, 3, 4, 5, 5, 5, 6]);
console.log(set.size); // 6
the array I passed in contains duplicates. But the set essentially strips them out leaving a collection of 6 unique items
You also have access to the add() method
let set = new Set();
set.add(1);
set.add('two');
console.log(set.size); // 2
Finally, there's the has() method, which is very useful. This method allows you to check if an item exists
console.log(set.has(1)); // true
console.log(set.has('two')); // true
console.log(set.has(3)); // false
Top comments (1)
It's amazing how many problems you can solve by having the proper data structure! It's nice to see JavaScript implementing these things as native language constructs.