Set In JavaScript

What is a Set in JavaScript?

A Set is a built-in collection in JavaScript that allows you to store unique values of any type. A Set automatically removes duplicate values and stores them in an ordered fashion. It's similar to an array but with a few key differences.

Key Characteristics of a Set:

  1. Unique Values: A Set can only contain unique values (no duplicates).

  2. No Indexes: A Set does not use indexes to access elements. You can't access elements by index, unlike arrays.

  3. Iterates in Insertion Order: The values in a Set are iterated in the order in which they were added.


Creating a Set

You can create a Set using the Set constructor:

const mySet = new Set();

Alternatively, you can initialize a Set with an array or other iterable object:

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

Basic Operations on a Set

1. Add Method

You can add elements to a Set using the add() method. If you try to add a duplicate value, it will be ignored.

const mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(2); // Duplicate value, will be ignored

console.log(mySet); // Output: Set { 1, 2, 3 }

2. Delete Method

The delete() method removes a specific element from the Set.

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

mySet.delete(2); // Removes 2 from the set

console.log(mySet); // Output: Set { 1, 3, 4 }

3. Has Method

The has() method checks if a particular element exists in the Set.

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

console.log(mySet.has(2)); // Output: true
console.log(mySet.has(4)); // Output: false

4. Size Property

The size property returns the number of unique elements in the Set.

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

console.log(mySet.size); // Output: 5

5. Clear Method

The clear() method removes all elements from the Set.

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

mySet.clear();

console.log(mySet); // Output: Set {}

Iterating Over a Set

You can iterate over a Set in several ways.

1. forEach Method

The forEach() method executes a provided function once for each element in the Set.

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

mySet.forEach((value) => {
  console.log(value);
});
// Output:
// 1
// 2
// 3

2. for...of Loop

You can use the for...of loop to iterate over the Set:

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

for (const value of mySet) {
  console.log(value);
}
// Output:
// 1
// 2
// 3

Comparison: Set vs. Array

FeatureSetArray
UniquenessStores only unique valuesCan store duplicate values
OrderMaintains insertion orderMaintains insertion order
AccessNo index-based access (iterable)Index-based access (e.g., arr[0])
DuplicatesDuplicates are automatically removedAllows duplicates
IterationSupports forEach, for...ofSupports forEach, for...of

Common Use Cases for Set

  1. Removing Duplicates: You can use a Set to remove duplicate values from an array.

     const numbers = [1, 2, 2, 3, 4, 4, 5];
     const uniqueNumbers = [...new Set(numbers)];
     console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
    
  2. Checking for Membership: A Set is very useful for checking if a value exists because of the fast lookup times.

     const uniqueSet = new Set([1, 2, 3, 4, 5]);
     console.log(uniqueSet.has(3)); // Output: true
     console.log(uniqueSet.has(6)); // Output: false
    
  3. Storing Unique Values from Multiple Arrays:

     const array1 = [1, 2, 3];
     const array2 = [3, 4, 5];
     const combinedSet = new Set([...array1, ...array2]);
     console.log([...combinedSet]); // Output: [1, 2, 3, 4, 5]
    

Summary of Key Methods

  • add(value): Adds a value to the Set.

  • delete(value): Deletes a specific value from the Set.

  • has(value): Checks if a value exists in the Set.

  • clear(): Removes all values from the Set.

  • size: Returns the number of values in the Set.