The Wayback Machine - https://web.archive.org/web/20250124085909/https://www.geeksforgeeks.org/sets-in-javascript/
Open In App

Set in JavaScript

Last Updated : 19 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Set in JavaScript is used to store a unique collection of items, meaning no duplicates are allowed.

  • Sets internally use a hash table which makes search, insert and delete operations faster than arrays. Please note that a hash table data structure allows these operations to be performed on average in constant time.
  • Set maintains insertion of items. When we access items, we get them in the same order as inserted.
  • Only Unique Keys are allowed, if we insert the same key with a different value, it overwrites the previous one.
  • A set can be created either empty or by providing an iterable like array or string.
JavaScript
// using an array
let s1 = new Set([10, 30, 30, 40, 40]);
console.log(s1);
let s2 = new Set(["gfg", "gfg", "geeks"]);
console.log(s2);

// using string
let s3 = new Set("fooooooood");
console.log(s3);

// an empty set
let s4 = new Set();
console.log(s4);

Output
Set(3) { 10, 30, 40 }
Set(2) { 'gfg', 'geeks' }
Set(3) { 'f', 'o', 'd' }
Set(0) {}

Methods of Set in JavaScript

  • Set.add() adds the new element with a specified value at the end of the Set object.
  • Set.delete() deletes an element with the specified value from the Set object. 
  • Set.clear() removes all the element from the set. 
  • Set.entries() returns an iterator object which contains an array having the entries of the set, in the insertion order. 
  • Set.has() returns true if the specified value is present in the Set object. 
  • Set.values() returns all the values from the Set in the same insertion order.
  • Set.keys() also returns all the values from the Set in the insertion order. 
  • Set.forEach() executes the given function once for every element in the Set, in the insertion order.
  • Set.prototype[@@iterator]() returns a Set iterator function which is values() function by default. 

Properties of Set in JavaScript

  • Set.size– It returns the number of elements in the Set.

Code Examples of Methods and Properties

1. Set add()

JavaScript
let s = new Set();

s.add(10);
s.add(20);

// As this method returns
// the set object hence chaining 
// of add method can be done.
s.add(30).add(40).add(50);

console.log(s);

console.log(s.size);

Output
Set(5) { 10, 20, 30, 40, 50 }
5

2. Set delete()

JavaScript
let s = new Set("foooodiiiieee");

// deleting e from the set
// it prints true
console.log(s.delete('e'));

console.log(s);

// deleting an element which is 
// not in the set
// prints false
console.log(s.delete('g'));

Output
true
Set(4) { 'f', 'o', 'd', 'i' }
false

3. Set clear()

JavaScript
let s = new Set([10, 20, 30, 40, 50]);

console.log(s);

s.clear()

console.log(s);

Output
Set(5) { 10, 20, 30, 40, 50 }
Set(0) {}

4. Set entries()

JavaScript
let s = new Set();

s.add(50);
s.add(30);
s.add(40);
s.add(20);
s.add(10);

// using entries to get iterator
let e = s.entries();

// each iterator is array of [value, value]
console.log(e.next().value);

console.log(e.next().value);

console.log(e.next().value);

Output
[ 50, 50 ]
[ 30, 30 ]
[ 40, 40 ]

5. Set has()

JavaScript
let s = new Set();

// adding element to the set
s.add(50);
s.add(30);
            
console.log(s.has(50));

console.log(s.has(10));

Output
true
false

6. Set values()

JavaScript
let s = new Set(['a', 'b', 'c']);
console.log(s.values());

Output
[Set Iterator] { 'a', 'b', 'c' }

7. Set keys()

JavaScript
let s = new Set(['a', 'b', 'c']);
let sk = s.keys();
console.log(sk);

Output
[Set Iterator] { 'a', 'b', 'c' }

8. Set forEach()

JavaScript
const mySet = new Set([1, 2, 3, 4]);

// Using forEach to iterate over the Set
mySet.forEach((value) => {
  console.log(value); 
});

Output
1
2
3
4

9. Set prototype[@@iterator]()

JavaScript
let s = new Set(["a","b","c"]);

let it = s[Symbol.iterator]();

console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());

Output
{ value: 'a', done: false }
{ value: 'b', done: false }
{ value: 'c', done: false }
{ value: undefined, done: true }

How to Check for Subset?

It returns true if Set A is a subset of Set B.  A Set A is said to be a subset of Set B, if all the elements of Set A is also present in Set B. Now lets implement and use the subset function. 

Here, we are checking whether the given subset is present in the given set or not and returning the result according to it.

JavaScript
Set.prototype.subSet = function(otherSet)
{
    // if size of this set is greater
    // than otherSet then it can't be 
    //  a subset
    if(this.size > otherSet.size)
        return false;
    else
    {
        for(let elem of this)
        {
            // if any of the element of 
            // this is not present in the
            // otherset then return false
            if(!otherSet.has(elem))
                return false;
        }
        return true;
    }
}

// using the subSet function

// Declaring different sets
let setA = new Set([10, 20, 30]);
let setB = new Set([50, 60, 10, 20, 30, 40]);
let setC = new Set([10, 30, 40, 50]);

// prints true
console.log(setA.subSet(setB));

// prints false
console.log(setA.subSet(setC));

// prints true
console.log(setC.subSet(setB));

Output
true
false
true

How to find Union?

It returns a Set which consists of the union of Set A and Set B. A Set is said to be a union of two sets, if it contains all elements of Set A as well as all elements of Set B, but it doesn’t contain duplicate elements. 

JavaScript
Set.prototype.union = function(otherSet)
{
    // creating new set to store union
    let res = new Set();

    // iterate over the values and add 
    // it to unionSet
    for (let x of this)
    {
        res.add(x);
    }

    // iterate over the values and add it to 
    // the unionSet
    for(let x of otherSet)
        res.add(x);

    // return the values of unionSet
    return res;
}

// using the union function
// Declaring values for set1 and set2
let s1 = new Set([10, 20, 30, 40, 50]);
let s2 = new Set([40, 50, 60, 70, 80]);  
let res = s1.union(s2);
console.log(res.values());

Output
[Set Iterator] { 10, 20, 30, 40, 50, 60, 70, 80 }

How to find Intersection?

It returns the intersection of Set A and Set B. A Set is said to be the intersection of Set A and B if contains an element which is present both in Set A and Set B. Let’s implement and use the intersection function 

JavaScript
Set.prototype.intersection = function(otherSet)
{
    // creating new set to store intersection
    let res = new Set();

    // Iterate over the values 
    for(let x of otherSet)
    {
        // if the other set contains a 
        // similar value as of value[i]
        // then add it to intersectionSet
        if(this.has(x))
            res.add(x);
    }
    return res;                
}

// using intersection function
// Declaring values for set1 and set2
let s1 = new Set([10, 20, 30, 40, 50]);
let s2 = new Set([40, 50, 60, 70, 80]);  
let res = s1.intersection(s2);

console.log(res.values());

Output
[Set Iterator] { 40, 50 }

How to find difference of two sets?

It returns the Set which contains the difference between Set A and Set B. A Set is said to be a difference between Set A and B if it contains set of elements e which are present in Set A but not in Set B. Let’s implement and use the difference function 

JavaScript
Set.prototype.difference = function(otherSet)
{
    // creating new set to store difference
    let res = new Set();

    // iterate over the values
    for(let x of this)
    {
        // if the value[i] is not present 
        // in otherSet add to the differenceSet
        if(!otherSet.has(x))
            res.add(x);
    }

    return res;
}

// using difference function
// Declaring values for set1 and set2
let s1 = new Set([10, 20, 30, 40, 50]);
let s2 = new Set([40, 50, 60, 70, 80]);  
let res = s1.difference(s2);

console.log(res);

Output
Set(3) { 10, 20, 30 }

DSA Problems On Set

Sets in JavaScript – FAQs

What is a Set in JavaScript?

A Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references. Unlike arrays, Sets automatically ensure that no duplicate values are present.

How do you create a Set?

You can create a Set using the Set constructor: const mySet = new Set();

How do you add values to a Set?

You can add values to a Set using the add() method, which takes one argument, the value to be added: mySet.add(1);

How do you check if a value exists in a Set?

You can check if a value exists in a Set using the has() method, which returns true if the value is present, and false otherwise: mySet.has(1);

How do you remove a value from a Set?

You can remove a value from a Set using the delete() method, which takes one argument, the value to be removed: mySet.delete(1);

How do you clear all values from a Set?

You can remove all values from a Set using the clear() method: mySet.clear();

How do you get the size of a Set?

You can get the number of values in a Set using the size property: mySet.size;



Next Article

Similar Reads

three90RightbarBannerImg