JavaScript:JavaScript Set: Unique Collections and Deduplication
JavaScript•Sets

JavaScript Set: Unique Collections and Deduplication

Set eliminates duplicates automatically and provides fast O(1) membership checks with .has().

Syntax

const mySet = new Set([1, 2, 2, 3]); mySet.add(4); mySet.has(2);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
add(val)MethodAppends a new unique element to the set.
has(val)MethodReturns boolean indicating whether element exists.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Deduplicating Arrays with Set
const rawTags = ["javascript", "react", "node", "react", "typescript", "node"];
const uniqueTags = [...new Set(rawTags)];

console.log("Raw Tags (length " + rawTags.length + "):", rawTags);
console.log("Unique Tags (length " + uniqueTags.length + "):", uniqueTags);

// Fast membership testing
const allowedRoles = new Set(["ADMIN", "SUPERUSER"]);
console.log("Is MODERATOR allowed?", allowedRoles.has("MODERATOR"));
console.log("Is ADMIN allowed?", allowedRoles.has("ADMIN"));
Expected Output:
Raw Tags (length 6): [ 'javascript', 'react', 'node', 'react', 'typescript', 'node' ]
Unique Tags (length 4): [ 'javascript', 'react', 'node', 'typescript' ]
Is MODERATOR allowed? false
Is ADMIN allowed? true

How It Works: Step-by-Step

  • Lines 2-3: Converts array with duplicates to Set and spreads back to unique array.
  • Lines 9-11: Demonstrates O(1) set membership check with has().

Key Concepts

  • new Set(array) instantly deduplicates primitive values.
  • Set uses SameValueZero equality (similar to ===, but considers NaN equal to NaN).
  • Set size is retrieved with the .size property.

Common Mistake: Expecting Set to deduplicate object references with identical properties

Two distinct object literals have different memory references and are not considered equal by Set.

❌ Incorrect
const s = new Set([{ id: 1 }, { id: 1 }]); // Set has size 2!
✅ Correct
const s = new Set();
const obj = { id: 1 };
s.add(obj);
s.add(obj); // Correct: only 1 entry

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler