Sets In JavaScript

Introduction

 
In this blog post, we are going to tackle Set, which is a collection of arbitrary unique values of any data type.
 
In other words, you can't really add duplicate values within a JavaScript Set. Not unlike an array is a bit more general-purpose and can have duplicate values.
 

Initialize a Set

 
A Set is created using a Set constructor, see the example below. 
  1. let myEmptySet= new Set();  
There are two ways you can initialize a Set. First, by an empty Set just like the example above. Second, you can create one by using the values of an iterable object. 
  1. let myArraySet = new Set(['mango''avocado''apple']); //mango avocado apple  
  2.   
  3. let programmingJs = new Set("JavaScript"); //J a v S c r i p t  
In our current example, the myArraySet variable initializes itself by passing an array of fruits, an array is an iterable object. Thus, it is accepted.
 
In the second example, we have passed a string. The string is accepted, it is because strings are an array of characters. Thus, it is accepted.
 
Another thing to point out, the variable programmingJs output is JavScript not JavaScript because duplicate values don't add up. 
 
Now, let us see what will happen if we pass a numerical value which is not an iterable object. It will definitely throw an exception.
  1. let anotherSet = new Set(4);  
  2. //Uncaught TypeError: number 4 is not iterable (cannot read property Symbol(Symbol.iterator))  

Set add() Method

 
Initializing an empty Set and appending a new element with a specified value, we can use the add() method. 
 
See the example below:
  1. let myFavoriteFoods = new Set();  
  2.   
  3. myFavoriteFoods.add('burger');  
  4. myFavoriteFoods.add('lasagna');  
  5. myFavoriteFoods.add('laksa');  
  6. myFavoriteFoods.add('burger');  
  7.   
  8. console.log(...myFavoriteFoods); //burger lasagna laksa  
As you can see in the example, we have added some random strings. However, in the last section of using the add() method, we've added the string burger again but it was not accepted by the Set and it didn't throw an error. 
 

Set Size Property

 
Now we have an idea of how to initialize a Set. Let's try to access the property size. 
  1. let japaneseCars = ['Toyota''Nissan''Mitsubishi'];  
  2.   
  3. let myCarCollection = new Set(japaneseCars);  
  4. console.log(`My total number of car number is ${myCarCollection.size}`);  
  5.  //My total number of car number is 3  
Looks easy to understand right? So, let's jump into the next part. 
 

Set has() Method

 
Sometimes we need to check if our current Set collection has a certain value exists. We can do that with the use of has() method.
  1. let cars = ['Toyota''Nissan''Mitsubishi''Ford''BMW'];  
  2.   
  3. let myCars = new Set(cars);  
  4.   
  5. console.log(`Does my car collection has a Ford brand? ${myCars.has('Ford')}`);  
  6. //Does my car collection has a Ford brand? true  
Again, looks easy to understand right? So, let's jump into the next part. 
 

Set clear() Method

 
What if we want to remove all of the elements within the Set. We can do that with the use of the clear() method.
  1. let myFavoriteNumbers = new Set();  
  2.   
  3. myFavoriteNumbers.add(23);  
  4. myFavoriteNumbers.add('23');  
  5. myFavoriteNumbers.add(120);  
  6. myFavoriteNumbers.add('120');  
  7.   
  8. console.log(...myFavoriteNumbers); //23 "23" 120 "120"  
  9.   
  10. myFavoriteNumbers.clear();  
  11.   
  12. console.log(myFavoriteNumbers.size); //0  
With our current example, we have declared a Set having a variable name of myFavoriteNumbers respectively. Then, we have added some random values to it. But with the use of the clear() method, everything was removed.
 

Set forEach() Method 

 
First, if you aren't familiar with forEach() method, you can check my previous article about it.
 
Hopefully, you have read my previous article. Now, going back, this forEach() method executes once for each value in the Set object, in insertion order.  
  1. let basketBallPlayers = new Set([{ name: 'Kobe Bryant', jersey: 24 },  
  2.                                  { name: 'Tim Duncan', jersey: 21 },  
  3.                                  { name: 'Larry Bird', jersey: 33 },  
  4.                                  { name: 'Magic Johnson', age: 32 },  
  5.                                  { name: 'Michael Jordan', jersey: 23 }]);  
  6.   
  7. basketBallPlayers.forEach((player) => {  
  8.     console.log(player);  
  9. });  

Output

Sets In JavaScript

 

Looks, straight-forward right? So let's jump to the next part.  
 

Set delete() Method 

 
Sometimes, we need to delete a specific item within the Set and we can do that with the help of delete() method.
 
Let's take the previous example and call the delete() method inside the forEach() method. See the example below. 
  1. let basketBallPlayers = new Set([{ name: 'Kobe Bryant', jersey: 24 },  
  2.                                  { name: 'Tim Duncan', jersey: 21 },  
  3.                                  { name: 'Larry Bird', jersey: 33 },  
  4.                                  { name: 'Magic Johnson', age: 32 },  
  5.                                  { name: 'Michael Jordan', jersey: 23 }]);  
  6.   
  7.   
  8. basketBallPlayers.forEach((player) => {  
  9.     if(player.name.toLowerCase() !== 'michael jordan'){  
  10.         basketBallPlayers.delete(player);  
  11.     }  
  12. });  
  13.   
  14. console.log(...basketBallPlayers);  

In the example above, we have deleted almost the Set basketBallPlayers except with Michael Jordan. 

 

Convert Set into an Array

 
Sometimes, we need to convert Set into an array. For any certain reasons, you can do that with the use of the Array.from() method. See the example below.
  1. const catNames = new Set();  
  2.   
  3. catNames.add("Zandro");  
  4. catNames.add("Ponpon");  
  5. catNames.add("Mikky");  
  6. catNames.add("Mamu");  
  7.   
  8. const petNames = Array.from(catNames);  
  9. console.log(petNames);  
Output

Sets In JavaScript
 

Summary

 
In this blog post, we have discussed JavaScript Sets. I hope you have enjoyed this blog post as much as I have enjoyed writing and coding the examples. Until next time, happy programming!