JavaScript Set

A Set is a built-in JavaScript object that stores a collection of unique values. No duplicates are allowed — if you add the same value twice, the Set keeps only one copy. Sets work with any type of value: numbers, strings, objects, or booleans.

How a Set Differs from an Array

An array allows duplicates and keeps values in order by index. A Set automatically removes duplicates and stores each value only once. Membership checks in a Set are also much faster than scanning an array.

Diagram: Array vs Set

Array:       [1, 2, 2, 3, 3, 3]
              ↑ duplicates allowed

Set:          {1, 2, 3}
              ↑ duplicates removed automatically

Creating a Set

// Empty Set
let mySet = new Set();

// Set from an array
let numSet = new Set([1, 2, 3, 2, 1]);
console.log(numSet); // Set(3) {1, 2, 3}

Core Set Methods

add( ) — Add a Value

let colors = new Set();

colors.add("red");
colors.add("green");
colors.add("blue");
colors.add("red"); // duplicate — ignored

console.log(colors); // Set(3) {"red", "green", "blue"}

has( ) — Check Membership

console.log(colors.has("red"));    // true
console.log(colors.has("yellow")); // false

delete( ) — Remove a Value

colors.delete("green");
console.log(colors); // Set(2) {"red", "blue"}

size — Count Items

console.log(colors.size); // 2

clear( ) — Remove All

colors.clear();
console.log(colors.size); // 0

Iterating Over a Set

Sets are iterable — you can loop through them with for...of or forEach.

let fruits = new Set(["apple", "banana", "mango"]);

for (let fruit of fruits) {
  console.log(fruit);
}
// apple
// banana
// mango

fruits.forEach(function(fruit) {
  console.log(fruit.toUpperCase());
});
// APPLE
// BANANA
// MANGO

Most Common Use: Removing Duplicates from an Array

Convert an array to a Set (duplicates drop out), then convert back to an array with the spread operator.

let votes = ["Alice", "Bob", "Alice", "Carol", "Bob", "Alice"];

let uniqueVoters = [...new Set(votes)];
console.log(uniqueVoters); // ["Alice", "Bob", "Carol"]
console.log(uniqueVoters.length); // 3

Diagram: Deduplication

Input array: ["Alice","Bob","Alice","Carol","Bob","Alice"]
                │
                ▼
        new Set(...)
                │
         (duplicates dropped)
                │
                ▼
        Set {"Alice","Bob","Carol"}
                │
                ▼
        [...Set] = array
                │
                ▼
Output: ["Alice","Bob","Carol"]

Set of Numbers

let lottery = new Set([5, 12, 7, 12, 3, 5, 18]);
console.log(lottery);      // Set(5) {5, 12, 7, 3, 18}
console.log(lottery.size); // 5

// Convert to sorted array
let sorted = [...lottery].sort((a, b) => a - b);
console.log(sorted); // [3, 5, 7, 12, 18]

Set Operations: Union, Intersection, Difference

JavaScript does not have built-in set operations yet (they are coming), but you can build them easily.

Union — All items from both sets

let a = new Set([1, 2, 3, 4]);
let b = new Set([3, 4, 5, 6]);

let union = new Set([...a, ...b]);
console.log(union); // Set(6) {1, 2, 3, 4, 5, 6}

Intersection — Items in both sets

let intersection = new Set([...a].filter(x => b.has(x)));
console.log(intersection); // Set(2) {3, 4}

Difference — Items in a but not in b

let difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference); // Set(2) {1, 2}

Diagram: Set Operations Visualized

Set A: {1, 2, 3, 4}
Set B: {3, 4, 5, 6}

    A only   │  Both  │  B only
  ┌──────────┼────────┼──────────┐
  │  1, 2    │  3, 4  │  5, 6    │
  └──────────┴────────┴──────────┘

Union:        {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference (A-B): {1, 2}

Set with Objects

Sets use reference equality for objects, not value equality. Two objects with the same content are treated as different unless they are the same reference.

let objA = { id: 1 };
let objB = { id: 1 };

let objSet = new Set();
objSet.add(objA);
objSet.add(objB); // different reference — both stored
objSet.add(objA); // same reference — ignored

console.log(objSet.size); // 2

Converting Between Set and Array

ConversionCode
Array to Setnew Set(array)
Set to Array[...set] or Array.from(set)

When to Use a Set vs an Array

SituationBest Choice
Need unique values onlySet
Need index access (arr[2])Array
Need to check if value exists (fast)Set
Need to sort or sliceArray (convert from Set first)
Removing duplicatesSet

Summary

A Set stores unique values of any type and automatically discards duplicates. The core methods — add, has, delete, and size — make it easy to manage collections without duplicates. Sets shine for deduplication, fast membership checks, and performing union, intersection, and difference operations on collections. When you need unique items, reach for a Set before writing deduplication logic manually.

Leave a Comment

Your email address will not be published. Required fields are marked *