ES6 sets a collection that cannot contain duplicates
Judith

Judith @jrohatiner

About: frontend software engineer. mental adventurist

Location:
miami beach/new york
Joined:
Oct 7, 2017

ES6 sets a collection that cannot contain duplicates

Publish Date: May 8 '18
10 1

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

Comments 1 total

  • Donald Merand
    Donald MerandMay 8, 2018

    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.

Add comment