loading...

Sets in JavaScript

attacomsian profile image Atta Updated on ・3 min read

JavaScript Revisited (15 Part Series)

1) How to show desktop notifications using JavaScript 2) Accepting Payments using JavaScript Payment Request API 3 ... 13 3) Understanding JSON.parse() and JSON.stringify() 4) Sets in JavaScript 5) Maps in JavaScript 6) Objects, Prototypes and Classes in JavaScript 7) Introduction to JavaScript Fetch API 8) Introduction to Service Workers in JavaScript 9) Getting DOM Elements using JavaScript 10) Introduction to JavaScript Arrow Functions 11) Introduction to JavaScript Regular Expressions 12) Introduction to XMLHttpRequest (XHR) 13) Object.entries() and Object.values() Methods in JavaScript 14) Using JavaScript Fetch API to Get and Post Data 15) Introduction to JavaScript URL Object

This post was originally published on attacomsian.com/blog.


A Set is a special type of object in ES6 that lets you create a collection of unique values. Each value appears only once in the set. The values stored in a set can be either primitive types (strings, numbers, booleans) or objects (object literals, arrays).

Initialize a Set

You can use the Set() constructor to create an empty set:

const birds = new Set();

Alternatively, you can pass an iterable object (like an array) to the constructor to initialize the set. All the elements in the iterable will be added to the new set:

const birds = new Set(['🐦', 'πŸ¦‰', 'πŸ¦†', 'πŸ¦…']);

Since strings are iterable, they can also be passed-in to create a set:

const fruits = new Set('πŸ’πŸ‡πŸ‰πŸ“πŸ‘');

Set Methods

Some of the methods you can use on a Set object are add(), has(), size, delete() and clear():

const birds = new Set();

// add items
birds.add('🐦');
birds.add('πŸ¦‰');
birds.add('πŸ¦†');
birds.add('πŸ¦…');

// check if item exists
birds.has('πŸ¦‰'); // true
birds.has('πŸ₯'); // false

// get items count
birds.size; // 4

// delete item
birds.delete('πŸ¦†'); // true
birds.delete('πŸ¦†'); // false - already deleted

// delete all items
birds.clear();

Since a set can only store unique values, calling add() with the same value multiple times won't add new items:

const birds = new Set();
birds.add('🐦');
birds.add('🐦');
birds.add('🐦');

birds.size; // 1

console.log(birds); // Set(1) {"🐦"}

Objects in Set

We can also put different objects types such as object literals, arrays, dates, etc. into the set:

const set = new Set(['πŸ¦‰', '🌹']);

set.add(['πŸ¦‰', '🍌']);
set.add({ name: 'John Doe', planet: 'Earth' });
set.add(new Date());

set.forEach(value => {
    console.log(value);
});

// πŸ¦‰
// 🌹
//Β ["πŸ¦‰", "🍌"]
// {name: "John Doe", planet: "Earth"}
// Thu May 16 2019 12:47:09 GMT+0100

Iterating over Sets

You can use forEach() to iterate over sets:

const flowers = new Set(['🌷', '🌹', '🌻', '🌸']);

flowers.forEach(flower => {
    console.log(`Hey ${flower}!`)
});

// Hey 🌷!
// Hey 🌹!
// Hey 🌻!
// Hey 🌸!

You can also use for...of loop to iterate over sets:

for (const flower of flowers) {
    console.log(flower);
}

Keys and Values

Sets also have keys() and values() methods just like Maps. The only exception is the keys() method is just an alias of values() method. Both return a new iterator object with the values in the same order as they were added to the set. We can also use these methods to iterate over the set:

const fruits = new Set('πŸ’πŸ‡πŸ‰πŸ“πŸ‘');

for (const k of fruits.keys()) {
    console.log(k);
}

for (const v of fruits.values()) {
    console.log(v);
}

We can also use the iterator to iterate over the set values one-by-one like the following:

const fruits = new Set('πŸ’πŸ‡πŸ‰');
const items = fruits.values();

console.log(items.next()); // {value: "πŸ’", done: false}
console.log(items.next()); // {value: "πŸ‡", done: false}
console.log(items.next()); // {value: "πŸ‰", done: true}

Calling next() returns each item as a {value: <value>, done: <boolean>} object until the iterator finishes, at which point the done is true. Sets have another method called entries() which also returns an iterator but the value is repeated twice:

const fruits = new Set('πŸ’πŸ‡πŸ‰');
const items = fruits.entries();

console.log(items.next()); // {value: ["πŸ’", "πŸ’"], done: false}

Conclusion

Sets are a new object type introduced in ES6 that allows you to create collections of values. A value can be either a primitive or an object and can occur only once in the set; it is unique in the collection. You can iterate through the values in an order they were inserted in the set.

If you want to learn more, check out our guide on maps in JavaScript.


✌️ I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter to get web development tutorials & protips every week.


Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.

JavaScript Revisited (15 Part Series)

1) How to show desktop notifications using JavaScript 2) Accepting Payments using JavaScript Payment Request API 3 ... 13 3) Understanding JSON.parse() and JSON.stringify() 4) Sets in JavaScript 5) Maps in JavaScript 6) Objects, Prototypes and Classes in JavaScript 7) Introduction to JavaScript Fetch API 8) Introduction to Service Workers in JavaScript 9) Getting DOM Elements using JavaScript 10) Introduction to JavaScript Arrow Functions 11) Introduction to JavaScript Regular Expressions 12) Introduction to XMLHttpRequest (XHR) 13) Object.entries() and Object.values() Methods in JavaScript 14) Using JavaScript Fetch API to Get and Post Data 15) Introduction to JavaScript URL Object

Posted on by:

attacomsian profile

Atta

@attacomsian

I write about modern JavaScript, Node.js, Spring Boot, and all things web development. Subscribe to my newsletter: https://attacomsian.com/newsletter

Discussion

markdown guide
 

There is a lot of value when using a Set over an Array.

I learned yesterday that Set#has(item) performs an O(log n) algorithm to determine if the value exists in it. I was able to get a small speed increase in my javascript for it.

Good article!

 

AFAIK, Set.has implementation in V8 is really fast - it has O(1) time complexity.

 

It's entirely possible I learned wrong! I took the statement at face value, knowing I couldn't verify it myself. If that's the case, then I'm really happy I use Set all the time now.

 

Is it correct to say that Set is like array, but with unique items only and Map is like object where keys might be of any type (not limited to strings and symbols)?

 

Well Set might look like an array but there are some notable differences. Apart from unique values, sets have different ways for initializing, accessing / adding / removing values.

 

Sets are also unordered lists of elements, unlike arrays.

Why? We can use forEach method on Sets to iterate the collection by insertion order.

Correct. Iteration is possible in the insertion order, but items are not indexed and they cannot be sorted unless converted to array beforehand. Maybe worth pointing out.

Agree. Sets also don't have array methods like map/filter/reduce and others. I just don't use Set/Map in my daily work and always forget what data structure is used for. By comparing Set to Array and Map to Object I want to create a mental connection in my head to remember the purpose of these data structures without looking in documentation.

 
 

Are set values unique, I can't remember, but if they are passing a string would be destructive, hello world would be helo wrd

 

Yes, Set values are unique. It will filter-out the duplicate characters if you pass a string to create a set.

 

So that's good for something I'm sure πŸ˜‹