Set - 2

When working with data, it’s often essential to keep a collection free of duplicates. Whether you’re cleaning an array, marking nodes as visited in a graph, or simply checking if a value exists, a Set offers a clean, efficient solution. This article walks through the core ideas behind Sets, their primary operations, and the scenarios where they shine.


Core Traits of a Set

  • Uniqueness – Every value can appear only once. Adding the same item again has no effect.
  • No Indexing – Sets are inherently unordered. Although JavaScript iterates in insertion order, you can’t access elements by numeric index.
  • Fast Membership Tests – Checking for existence is essentially O(1), far quicker than scanning an array.
  • Special Equality Rules – Sets use the SameValueZero algorithm: NaN is considered equal to itself, and objects are compared by reference.

Creating and Manipulating a Set

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

set.add(1);                     // Add a number
set.add('hello');               // Add a string
set.add(1);                     // Ignored – duplicate
set.add({ a: 1 });              // Object stored by reference

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

set.has(1);                     // true – element exists
set.delete('hello');            // removes the string, returns true
set.clear();                    // empties the set

You can also initialize a Set with an iterable; duplicates are automatically removed:

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

Iterating Over a Set

A Set is iterable, so you can use any loop construct that accepts iterables.

const letters = new Set(['a', 'b', 'c']);

for (const letter of letters) {
  console.log(letter);
}

letters.forEach(value => console.log(value)); // same output

The keys(), values(), and entries() methods are available, but note that entries() yields [value, value] pairs because a Set has only values, no distinct keys.


Converting Between Sets and Arrays

The spread operator and Array.from() make conversions trivial.

// Set → Array
const unique = [...new Set([1, 2, 3])];
const other = Array.from(new Set([1, 2, 3]));

// Array → Set
const setFromArray = new Set([1, 2, 3]);

These patterns are handy for tasks like deduplication or preparing data for functions that expect arrays.


Practical Use Cases

1. Removing Duplicates

A single line can clean an array:

const raw = [1, 2, 2, 3, 4, 4, 5];
const cleaned = [...new Set(raw)];   // [1, 2, 3, 4, 5]

2. Set Operations

Sets simplify classic set algebra:

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

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

// Intersection
const intersection = new Set([...a].filter(x => b.has(x))); // {3,4}

// Difference (a \ b)
const difference = new Set([...a].filter(x => !b.has(x))); // {1,2}

3. Tracking Visited Items

In graph traversals, web crawlers, or any algorithm that must avoid revisiting elements, a Set is ideal:

const visited = new Set();

function explore(node) {
  if (visited.has(node)) return; // Skip already processed nodes
  visited.add(node);
  // …process node…
}

Set vs. Array: A Quick Comparison

Feature Set Array
Uniqueness Automatic deduplication Allowed duplicates
Membership O(1) O(n)
Indexing No Yes (by numeric index)
Iteration Insertion order Insertion order
Typical Use Deduplication, fast lookup Ordered data, indexing

When to choose which?

  • Set: Frequent existence checks, deduplication, or when you only care about the presence of items.
  • Array: When order matters, you need indexed access, or duplicates are acceptable.

Beyond the Basics

If you need to store object references without preventing garbage collection, consider WeakSet. It behaves like a Set but holds weak references, allowing objects to be collected when no other references exist.


Takeaway

A Set is a lightweight, efficient tool for any scenario that demands uniqueness or rapid membership tests. Mastering its syntax and common patterns—deduplication, set algebra, and visited tracking—lets you write cleaner, faster JavaScript code. Choose a Set when the data’s identity matters more than its position; otherwise, an Array remains the go‑to structure.