DEV Community

Judith
Judith

Posted on

ES6 sets a collection that cannot contain duplicates

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Try it on jsbin

Top comments (1)

Collapse
 
dmerand profile image
Donald Merand •

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.