An Introduction to Sets in JavaScript

An Introduction to Sets in JavaScript

Using sets to deal with unique elements in a dataset

Image for postPhoto by JOSHUA COLEMAN on Unsplash

Sets are a new object type included in ES6 that allow the creation of collections of unique values. The values in a set can be either simple primitives like strings and integers or more complex object types like object literals or arrays. Think of sets as an array with no repeated elements.

There are many instances where we have an array containing many elements that we want to convert to a unique array. While it can be done by brute force on the array, checking elements, using loops, distinct callback method, etc., the best method is using set().

Syntax:

new Set([iterable]);

Let?s first see an example:

It is clear from the example that by making a new set from an array and using the spread operator, you can make a set into an array.

Set Methods

Now let’s look at some basic set methods, you may not need them but it best to be familiar with them in order to optimize your code:

  • add
  • size
  • has
  • forEach
  • delete
  • clear

It?s pretty much straight forward, the add method adds elements, the delete method deletes them, the has method has the same functionality as includes in arrays, and the clear method empties the set.

As we saw in the syntax, the set method takes an iterable as an argument, so a string can also be used as an argument.

Now let?s look at the practical examples of the set method:

Conclusion

In the end, I want to conclude that sets should be used when dealing with distinct or unique elements in a dataset. Arrays should be the preferred choice first and foremost as they have enough methods and functions for dealing with almost every question.

21