JavaScript Sets

Understanding Sets - Collections of unique values

🎯 What are JavaScript Sets?

A Set is a collection of unique values. Unlike arrays, Sets automatically remove duplicate values and provide efficient methods for checking if a value exists.


// Creating a new Set
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // Duplicate - won't be added
console.log(mySet); // Set {1, 2}
                                    

Output:

Set {1, 2}

Key Set Features

🔄

Unique Values

Automatically removes duplicates

const set = new Set([1, 1, 2, 3]);
// Result: Set {1, 2, 3}

Fast Lookup

Quick checking if value exists

set.has(2); // true
set.has(5); // false
📏

Size Property

Get number of unique values

set.size; // 3
🔄

Iterable

Can be looped through

for (let value of set) {
  console.log(value);
}

🔹 Creating Sets

There are several ways to create a Set:

// Empty Set
const emptySet = new Set();

// Set from array
const arraySet = new Set([1, 2, 3, 4]);

// Set from string (each character)
const stringSet = new Set('hello');
console.log(stringSet); // Set {'h', 'e', 'l', 'o'}

// Set with mixed data types
const mixedSet = new Set([1, 'hello', true, null]);
console.log(mixedSet); // Set {1, 'hello', true, null}

Output:

Set {'h', 'e', 'l', 'o'}
Set {1, 'hello', true, null}

🔹 Basic Set Operations

Common operations you can perform with Sets:

const fruits = new Set();

// Adding values
fruits.add('apple');
fruits.add('banana');
fruits.add('orange');
fruits.add('apple'); // Won't be added (duplicate)

console.log(fruits.size); // 3

// Checking if value exists
console.log(fruits.has('apple')); // true
console.log(fruits.has('grape')); // false

// Removing values
fruits.delete('banana');
console.log(fruits.has('banana')); // false

// Clear all values
fruits.clear();
console.log(fruits.size); // 0

Output:

3
true
false
false
0

🔹 Practical Set Examples

Real-world use cases for Sets:

🔸 Remove Duplicates from Array

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Output:

[1, 2, 3, 4, 5]

🔸 Check Common Elements

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

// Find intersection (common elements)
const intersection = new Set([...set1].filter(x => set2.has(x)));
console.log(intersection); // Set {2, 3}

Output:

Set {2, 3}

🧠 Test Your Knowledge

What happens when you add a duplicate value to a Set?