iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Sets

A Set is a collection of unique values. Adding a duplicate is a no-op. Useful for de-duplication, membership tests, and tracking visited items.

Creating & using

JS
const tags = new Set();
tags.add("html");
tags.add("css");
tags.add("html");        // no-op — already present
tags.size;               // 2
tags.has("html");        // true
tags.delete("css");
tags.clear();

// Build from an iterable
const unique = new Set([1, 2, 2, 3, 3, 3]);   // Set(3) { 1, 2, 3 }

// Iterate values
for (const tag of tags) console.log(tag);
tags.forEach(t => console.log(t));

Most common use: deduplicate an array

JS
const dedup = [...new Set([1, 1, 2, 3, 3, 4])];   // [1, 2, 3, 4]

Set vs. Array

NeedPick
Ordered list with possible duplicatesArray
Unique items, fast has(x)Set
Index access (arr[0])Array
Map-like behaviour with non-string keysMap (next lesson)

Operations

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

const union        = new Set([...a, ...b]);                  // {1,2,3,4}
const intersection = new Set([...a].filter(x => b.has(x)));   // {2,3}
const difference   = new Set([...a].filter(x => !b.has(x)));  // {1}
Tip: A Set's has is roughly O(1); calling Array.includes in a hot loop is O(n). When membership matters, the Set wins by orders of magnitude.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Sets!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Deduplicate an array using a Set.

const unique = [...new (arr)];

Test yourself

Q1. Adding a value already present in a Set…
Q2. Deduplicate an array `[1,1,2,3,3]` quickly with…
Q3. Membership test on a Set is…

Discussion

Loading…