Set In JavaScript

Introduction

 
We all are familiar with the data structure called Array and it is used to store a collection of data and the collection can be string, numbers, objects, etc. An array can contain duplicate items. If we have a requirement for removing the duplicates from the array, we would need to write some logic that may contain loops, conditions, etc. But if we use Set we can avoid this. 
 

What is Set? 

 
Set object lets us store elements without any duplicates. Set is a collection of unique elements. Set can have values of different data types which includes objects as well.
 
If we try to add an already existing item to a Set, it won't accept that value. The main difference between arrays is, the set is not an indexed collection.
Below are the methods used in Set object,
 
Creating a new Set,
  1. let mySet = new Set();  
Adding a new item into the Set,
  1. mySet.add(1); //[1]  
  2. mySet.add(2); //[1,2]  
  3. mySet.add(3); //[1,2,3]  
Removing an item from the Set
  1. mySet.delete(3); //[1,2]  
Trying to an already existing item into the Set,
  1. mySet.add(2); //[1,2] there will not be any change in the data  
Adding data of different type,
  1. mySet.add('Test'); //[1,2,'Set']  
Checking the size of Set
  1. mySet.size; //3  
Checking whether an element is existing in the Set or not,
  1. mySet.has(2) //true  
  2. mySet.has(5) //false  
Clearing all the data from the Set,
  1. mySet.clear()  
  2. mySet.size; //0  
Iterating through a Set,
  1. let mySet = new Set();  
  2. mySet.add(1);  
  3. mySet.add(2);  
add methods returns the updated Set and we can chain the add method as below, 
  1. mySet.add('test').add(true);  
  2. for (const item of mySet) {  
  3.     console.log(item); //1 2 'test' true  
  4. }  
  5. or  
  6. mySet.forEach(item => {  
  7.     console.log(item);  
  8. });  
Converting an array to Set,
  1. const numbers=[1,2,3,1,3,2];  
  2. const uniqueNumbers=new Set(numbers); //New Set contains [1,2,3]  
Converting Set to Array,
  1. const tmpArray = [...uniqueNumbers] //new array will be [1,2,3], this is converted using spread operator  
  2. or  
  3. const tmpArray = Array.from(uniqueNumbers);  
Set cannot replace arrays as both are different concepts. Arrays has a lot of useful methods when compared with Sets. Hence Set cannot be used when we have a lot of data manipulation activities.