patternjavascriptTip
Set for deduplication and O(1) membership testing
Viewed 0 times
Set: ES2015; set operations: ES2024
Setdeduplicationunique arraymembership testset operations
Problem
Deduplicating arrays with filter + indexOf is O(n squared). Testing membership in a large array is O(n). Both are common performance footguns.
Solution
Use Set for O(1) membership and O(n) deduplication.
const unique = [...new Set([1, 2, 2, 3])];
// [1, 2, 3]
const validCodes = new Set(['USD', 'EUR', 'GBP']);
validCodes.has('USD'); // true — O(1)
// ES2024 set operations
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
a.union(b); // Set {1, 2, 3, 4}
a.intersection(b); // Set {2, 3}
const unique = [...new Set([1, 2, 2, 3])];
// [1, 2, 3]
const validCodes = new Set(['USD', 'EUR', 'GBP']);
validCodes.has('USD'); // true — O(1)
// ES2024 set operations
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
a.union(b); // Set {1, 2, 3, 4}
a.intersection(b); // Set {2, 3}
Why
Set uses a hash-based structure internally, giving O(1) for has(), add(), and delete(). Array.includes is O(n). For large collections the difference is significant.
Gotchas
- Set uses SameValueZero equality — NaN equals NaN, -0 equals +0
- Set preserves insertion order
- Objects are compared by reference — new Set([{a:1},{a:1}]) has size 2
- Set.union/intersection/difference are ES2024 — use spread or filter for older targets
Code Snippets
Set for deduplication and O(1) lookup
// Dedup IDs
const uniqueIds = [...new Set([1, 2, 2, 3])];
// Fast membership check
const blocked = new Set(blockedUserIds);
if (blocked.has(userId)) return 403;
// ES2024 set math
const admins = new Set(['alice', 'bob']);
const online = new Set(['bob', 'carol']);
const onlineAdmins = admins.intersection(online); // Set {'bob'}Revisions (0)
No revisions yet.