Loading...

Sets in JavaScript – How to work with set data structure in JS

Sets in JavaScript – How to work with set data structure in JS

Set is a data structure that was first introduced in ECMAScript 6. A Set holds a collection of values much like Arrays but it can only contain unique elements; Each value in a Sets occurs only once.

Whether you’re new to JavaScript or a seasoned programmer, the Set data structure can come in handy in many scenarios. In this article, we will look at what is Set data structure in JavaScript, why we would want to use Sets in our programs, along with its syntax.

What is a Set?

A Set is basically a collection of unique values, i.e., one value can occur only once in a Set. If we try to insert a value that is already present in the Set, it is simply ignored. The values stored in a Set can be of any type, whether it is a primitive type or object references.

One important thing to note is that Sets in JavaScript are ordered. The order of values followed by Sets is the insertion order, i.e., the order in which the values were inserted into the Set.

Why should we use Sets?

Now that we know what is a Set, a question might arise; Why should we use Sets in place of Arrays? If we want to have unique elements in an Array, we can simply check if the value already exists by using the Array.prototype.includes() method.

The benefits of using a Set come down to the optimization and performance benefits. Sets are internally implemented as hash tables or search trees that give us a constant O(1) or O(logN) lookup time in searching an element. Although different browsers or JavaScript engines may implement Set differently, it is always guaranteed to give us time complexity better than O(N).

So if you are working with a large collection of values and you are only concerned with the unique values, using a Set is your best bet. With that being said, let us look at how we can create Sets in JavaScript and carry out different operations that we can perform on them.

Syntax

Now that we understand what are Sets and why Sets are useful, let us see how can work with Sets in JavaScript.

Declaring and Initializing a Set

We can create an empty Set object by using the new keyword as follows,

const myNewSet = new Set();
Code language: JavaScript (javascript)

This will create a Set named myNewSet which we can then use to add, remove, or access values.

We can also initialize a Set with values by passing an Array to the constructor,

const myNewSet = new Set(["here" , "are", "are", "some", "values"]); console.log([...myNewSet]); // ["here", "are", "some", "values"]
Code language: JavaScript (javascript)

We can create a Set of unique characters in a string by just passing the string to the Set constructor,

const myNewSet = new Set("here"); console.log([...myNewSet]); // ["h", "e", "r"]
Code language: JavaScript (javascript)

Adding values

We can add new values to a Set by using the add() method on the Set object and passing the new value as a parameter. Let us see an example of the same,

const myNewSet = new Set([1, 4, 6]); myNewSet.add(7); // added myNewSet.add(1); // already exists in Set, ignored console.log([...myNewSet]); // [1, 4, 6, 7]
Code language: JavaScript (javascript)

Deleting values

We can remove a specific value from a Set by using the delete() method on the Set object. The method returns true if an element is removed and false if there was no element with that value in the Set.

const myNewSet = new Set([1, 4, 6]); console.log(myNewSet.delete(1)); // true console.log(myNewSet.delete(5)); // false console.log([...myNewSet]); // [4, 6]
Code language: JavaScript (javascript)

Deleting all elements

We can remove all the elements of a set and make it empty by using the clear() methods on the Set object. Let us see an example below,

const myNewSet = new Set([1, 4, 6]); myNewSet.clear(); console.log([...myNewSet]); // []
Code language: JavaScript (javascript)

Checking if a value exists

We can check if a value exists in the Set by calling the has() method on the Set object and passing the value we want to check for. As discussed previously, the lookup time for a Set is O(1) in the best case which is far better than the Array includes() method which has a linear lookup time of O(N).

The method returns true if the value passed in the parameter exists in the Set or false otherwise,

const myNewSet = new Set([1, 4, 6]); console.log(myNewSet.has(1)); // true console.log(myNewSet.has(5)); // false
Code language: JavaScript (javascript)

Looping through elements

There are a few ways of looping through each element of a Set. Let us look at a couple of them.

Firstly, we can use the forEach() method on a Set object. A function has to be passed to the method which runs once for each element of the Set. We can use it to simply print each element or do any required operations. Let us see an example of the same,

const myNewSet = new Set([1, 4, 6]); myNewSet.forEach(element => { console.log(element); });
Code language: JavaScript (javascript)

Output

1 4 6
Code language: Bash (bash)

Alternatively, we can also use the for...of loop to iterate over the elements of a Set. The for...of loop lets us iterate over iterable objects such as Sets, Maps, and arrays. An example of this can be seen below,

const myNewSet = new Set([1, 4, 6]); for (const element of myNewSet) { console.log(element); }
Code language: JavaScript (javascript)

Output

1 4 6
Code language: Bash (bash)

Check the number of elements

We can view the number of elements present in a set by using the size property on the Set object,

const myNewSet = new Set([1, 4, 6]); console.log(myNewSet.size); // 3
Code language: JavaScript (javascript)

Converting to Iterator

You can convert a Set to an Iterator by calling the values() on the Set object. The method will return an iterator with all the elements of the Set object. You can then use this Iterator object to iterate over the elements of the Set. Let us see an example of using the values() method and using the iterator to loop through the Set,

const myNewSet = new Set([1, 4, 6]); const iterator = myNewSet.values(); for (const element of iterator) { console.log(element); }
Code language: JavaScript (javascript)

Important methods and properties at a glance

Let us now look at some of the important methods and properties of Sets using the table below,

new Set()Create a new Set object.
add()Add a new element to the Set.
has()Check if an element is present in the Set.
delete()Delete a specified value from the Set.
clear()Delete all elements from the Set.
forEach()Run a specified function for every element of the Set.
values()Return an Interator with all the values present in the Set.
sizeProperty to check the number of elements in the Set.

Conclusion

In this article, we looked at what Sets are in JavaScript, why we would want to use Sets in our JavaScript programs, along with the syntax for creating, modifying, and working with Sets in JavaScript.

Sets can work as a better alternative to arrays in a lot of situations as we discussed before. I hope this article has helped you get a better understanding of Sets in JavaScript, and you will be comfortable using Sets in your next project wherever required.

If you have any questions regarding this article or want to talk about anything technology, you can find me on Twitter. Thank you for reading!

Sharing is caring

Did you like what Supantha Paul wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far