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,
Adding a new item into the Set,
- mySet.add(1);
- mySet.add(2);
- mySet.add(3);
Removing an item from the Set
Trying to an already existing item into the Set,
Adding data of different type,
Checking the size of Set
Checking whether an element is existing in the Set or not,
- mySet.has(2)
- mySet.has(5)
Clearing all the data from the Set,
- mySet.clear()
- mySet.size;
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);
- }
- 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);
Converting Set to Array,
- const tmpArray = [...uniqueNumbers]
- 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.