My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Set in javascript

Asmit shrivastava's photo
Asmit shrivastava
·Jun 15, 2021·

2 min read

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,

let mySet = new Set();

Adding a new item into the Set,

mySet.add(1); //[1]  
mySet.add(2); //[1,2]  
mySet.add(3); //[1,2,3]

Removing an item from the Set

mySet.delete(3); //[1,2]

Trying to an already existing item into the Set,

mySet.add(2); //[1,2] there will not be any change in the data

Adding data of different type,

mySet.add('Test'); //[1,2,'Set']

Checking the size of Set

mySet.size; //3

Checking whether an element is existing in the Set or not,

mySet.has(2) //true  
mySet.has(5) //false

Clearing all the data from the Set,

mySet.clear()  
mySet.size; //0

Iterating through a Set,

let mySet = new Set();  
mySet.add(1);  
mySet.add(2);

add methods returns the updated Set and we can chain the add method as below,

mySet.add('test').add(true);  
for (const item of mySet) {  
    console.log(item); //1 2 'test' true  
}  
or  
mySet.forEach(item => {  
    console.log(item);  
});

Converting an array to Set,

const numbers=[1,2,3,1,3,2];  
const uniqueNumbers=new Set(numbers); //New Set contains [1,2,3]

Converting Set to Array,

const tmpArray = [...uniqueNumbers] //new array will be [1,2,3], this is converted 
using spread operator  
or  
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.

That's it

If you have any doubts , drop them in the comments below. Thank you for reading