snippetjavascriptTip
Set operations: union, intersection, and difference without libraries
Viewed 0 times
set unionset intersectionset differenceset operationscollections
Problem
JavaScript's Set has no built-in union, intersection, or difference methods. Developers either reach for lodash or write O(n^2) nested loops instead of O(n) Set-based operations.
Solution
Implement the three core operations using Set spread and filter. All three run in O(n) average time due to Set.has() being O(1).
Why
Set.has() is O(1) average (hash table lookup). Spreading into arrays and using .filter() composes cleanly. ES2025 adds Set.prototype.union/intersection/difference natively but browser support is still partial.
Gotchas
- Set equality is reference-based for objects — Sets of objects won't deduplicate by value
- Spreading large Sets into arrays allocates memory — for huge sets use iterators
- The native ES2025 Set methods return new Sets and don't mutate — match that contract in your own implementations
Code Snippets
Set union, intersection, and difference
const union = (a, b) => new Set([...a, ...b]);
const intersection = (a, b) => new Set([...a].filter(x => b.has(x)));
const difference = (a, b) => new Set([...a].filter(x => !b.has(x)));
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
console.log([...union(a, b)]); // [1,2,3,4,5,6]
console.log([...intersection(a, b)]); // [3,4]
console.log([...difference(a, b)]); // [1,2]Context
Comparing collections, finding common elements, or computing differences between lists
Revisions (0)
No revisions yet.