Latest

ESNext — Sets

This is the second post in our on-going series Introducing ESNext. Last time, we talked about the Map data structure. Now we'll be discussing the Set data structure and its new support in ES6.

Sets

A Set is a pretty simple concept. You can think of them as an array, where every item is unique.

var primeNumbers = new Set();

primeNumbers.add(3);
// primeNumbers.size => 1

primeNumbers.add(5);
// primeNumbers.size => 2

primeNumbers.add(3);
// primeNumbers.size => 2

As you can see, a duplicate item won't be added since it already exists in the Set.

Internally, Sets are implemented on Map, so they have some interesting characteristics. You can store complex objects and class instances and they're "duplicates" will be correctly detected. This also makes finding and deleting items very fast since it's basically a Map key lookup instead of iterating over an array until the correct index is found.

Sets can be initialized with an initial array:

var firstNames = new Set([
    "Erin", "Pat", "Kate", "Bob",
    "Erin, "Jake", "Sarah"
]);
// firstNames.size => 6

Checking for the existence of a item in a set uses the has function:

firstNames.has("Kate") => true

firstNames.has("Kevin") => false

Items can be removed from Sets or the Set can be cleared entirely:

firstNames.remove("Jake")
// firstNames.size => 5

firstNames.clear();
// firstNames.size => 0

Finally, Sets can be iterated in 2 ways. Either using the more generic "for of" support in ES6 or with a forEach iterator.

for (var name of firstNames) {
    console.log(name);
}

// or

firstNames.forEach(function(name) {
    console.log(name);
});

So, if you never want to worry about duplicate items and are happy to save a few cycles finding and removing items from a list, the Set is the data structure for you.

Related