A Set is a built-in collection of unique values. Values in a Set occur only once; duplicate insertions are ignored. Sets can hold both primitive values and object references.
flowchart LR
ArrayColl["Array: [1, 2, 2, 3] (Allows Duplicates)"]
SetColl["Set: Set(3) {1, 2, 3} (Guarantees Uniqueness)"]
| Method / Property | Signature | Description |
|---|---|---|
size |
set.size |
Returns count of unique elements in set. |
add(val) |
set.add(val) |
Appends value to set; returns updated set (chainable). |
delete(val) |
set.delete(val) |
Removes value; returns true if item was present. |
has(val) |
set.has(val) |
Fast $O(1)$ lookup check returning boolean. |
clear() |
set.clear() |
Removes all elements from set. |
// Demonstrating Set operations, deduplication, and ES2024 Set methods
// 1. Array Deduplication via Set
const duplicateArray = ["admin", "editor", "admin", "guest", "editor"];
const uniqueRolesSet = new Set(duplicateArray);
console.log("Unique Roles Set:", uniqueRolesSet);
const deduplicatedArray = [...uniqueRolesSet];
console.log("Deduplicated Array:", deduplicatedArray);
// 2. Fast Membership Testing with has()
console.log(`Has 'editor' role? ${uniqueRolesSet.has("editor")}`); // true (O(1) complexity)
// 3. Set Operations (Union & Intersection)
const setA = new Set(["A", "B", "C"]);
const setB = new Set(["B", "C", "D"]);
// Union (Combine unique elements)
const union = new Set([...setA, ...setB]);
console.log("Union Set:", [...union]); // ['A', 'B', 'C', 'D']
// Intersection (Common elements)
const intersection = new Set([...setA].filter((item) => setB.has(item)));
console.log("Intersection Set:", [...intersection]); // ['B', 'C']
Set.has(val) instead of Array.includes(val) ($O(n)$) when performing frequent existence checks on large datasets.Set, NaN is treated as equal to NaN, so a Set can contain at most one NaN value.{ id: 1 } and { id: 1 } are treated as unique entries because they store different memory pointers.Deduplicate an array [1, 2, 2, 3, 4, 4, 5] into a clean unique array in a single line of code using Set and spread syntax.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.