JavaScript Sets

A Set in JavaScript is a collection of unique values. It allows you to store distinct elements, be it primitive values or object references.

Key Characteristics of Sets:

  • Unique values: No duplicate items are allowed in a Set.
  • Order: Elements in a Set are stored in the order of insertion.
  • Iterable: Sets are iterable, meaning you can loop through the elements.

Creating a Set:

You can create a Set using the Set constructor.

let mySet = new Set();

Try It Now

You can also initialize a Set with an array or any iterable object.

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

Try It Now

Adding Elements:

Use the add() method to add elements to a Set.

mySet.add(5);
mySet.add(1); // Duplicate, won't be added

Try It Now

Checking for Elements:

Use the has() method to check if an element is in the Set.

mySet.has(3); // true
mySet.has(10); // false

Try It Now

Removing Elements:

  • Remove a specific element: Use the delete() method.
    mySet.delete(3); // Removes 3 from the Set
    

    Try It Now

  • Remove all elements: Use the clear() method.
    mySet.clear(); // Clears all elements from the Set
    

    Try It Now

Set Properties:

  • size: Returns the number of elements in the Set.
    console.log(mySet.size); // 4
    

    Try It Now

Iterating Over a Set:

You can iterate through a Set using various methods:

  • for...of loop:
    for (let item of mySet) {
      console.log(item);
    }
    

    Try It Now

  • forEach method:
    mySet.forEach((value) => {
      console.log(value);
    });
    

    Try It Now

Common Operations:

  • Union: Combine two Sets.
    let setA = new Set([1, 2, 3]);
    let setB = new Set([3, 4, 5]);
    let union = new Set([...setA, ...setB]); // {1, 2, 3, 4, 5}
    

    Try It Now

  • Intersection: Find common elements.
    let intersection = new Set([...setA].filter(x => setB.has(x))); // {3}
    

    Try It Now

  • Difference: Find elements in one Set but not the other.
    let difference = new Set([...setA].filter(x => !setB.has(x))); // {1, 2}
    

    Try It Now

Use Cases for Sets:

  • Removing duplicates from an array.
  • Performing set operations (union, intersection, difference).
  • Keeping track of unique items.

Example:

let numbers = new Set([1, 2, 3, 4, 5]);

numbers.add(6);
console.log(numbers.has(5)); // true
numbers.delete(3);
console.log(numbers.size); // 5

numbers.forEach((value) => {
  console.log(value);
});

Try It Now

Sets are efficient for ensuring unique elements and performing operations like union and intersection. They offer a simple API and are a useful addition to JavaScript’s collection types.