Skip to main content

Command Palette

Search for a command to run...

Set in JavaScript

Published
•3 min read•View as Markdown
Set  in  JavaScript

Hi everyone! in this article, we will learn what is a set, and the applications of a set.

In Javascript, the set is a collection of unique items and we can store any type of data in a set like primitives(number, string, boolean) or objects. But keep in mind, the set doesn't store duplicate items. It will discard duplicate items.

Set methods

A set object provides many methods to add, delete and check if an item present in the set. Let's understand them one by one with an example.

  • add( item )

    It inserts an item into the set.

let s = new Set();
s.add(1);
s.add(2);
s.add(1); // already exists, so set discard it.

console.log(s); // Set {1,2};
  • delete( item )

    It deletes the specified item from the set and returns a boolean value if the item was deleted successfully or not.

let s = new Set();
s.add("Apple");
s.add("Orange");

s.delete("Orange"); // true
s.delete("mango"); // false
  • has( item )

It checks if the specified item is present in the set or not.

let s = new Set();
s.add("Batman");
s.add("Spiderman");

s.has("Batman"); // true
s.has("Ironman"); // false
  • size()

    It returns the number of items in the set.

    let s = new Set();
    
    s.add("Batman");
    s.add("Spiderman");
    
    s.size(); // 2
    

How to iterate/access set items?

We can use the "for...of" loop or the "forEach" loop to access set items.

let s = new Set();
s.add(1);
s.add(3);
s.add("Batman");

//for...of
for(let item of s){
  console.log(item); // 1,3,Batman
}

//forEach
s.forEach( item => {
    console.log(item); // 1,3,Batman
});

Convert an array into a set

We can easily convert an array into a set. Just pass an array as an argument into a set constructor function.

let heroes = ["Batman","Spiderman","Ironman"];
let heroSet = new Set(heroes);

heroSet.has("Batman"); //true
console.log(heroSet);// Set{"Batman","Spiderman","Ironman"} 

// Convert a set into an array
let arr = [...heroSet];
console.log(arr);// ["Batman","Spiderman","Ironman"]

Application of set

If you have gained knowledge of something, but don't know how to use it to make your life easier or solve some problem then that knowledge doesn't add much value to you.

Let's see how we can use the set to solve some coding problems.

Remove duplicate values from an array

let arr = [1,2,1,3,2,5];

//first convert arr into a set
let set = new Set(arr);

// convert set into arr
let unique_arr = [...set];
console.log(unique_arr); // 1,2,3,5

Find common items between two arrays

let arr1 = [1,2,4,6,7];
let arr2 = [9,3,4,1,0];

//convert both arrays to set
let set1 = new Set(arr1);
let set2 = new Set(arr2);

let commonItems = []; // Store common items 

for(let item of set1){
    if(set2.has(item)){
        commonItems.push(item);
    }
}

console.log(commonItems); // [1,4]

More from this blog

Ajay's blog

32 posts