Common Set Operations
You'll learn: How to combine, compare, and filter Sets using union, intersection, and difference operations.
The Core Idea
Sets in math have classic operations: union (all items from both sets), intersection (only items in both), and difference (items in one but not the other). JavaScript doesn't provide these as built-in methods, but you can implement them easily using the Set methods you already know.
Think of it like Venn diagrams: Union fills the entire diagram, intersection is the overlapping middle, and difference is just one circle minus the overlap.
Union: Combining Sets
Union creates a new Set containing all unique elements from both sets:
const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);
const union = new Set([...setA, ...setB]);
console.log(union); // Set { 1, 2, 3, 4, 5 }
Intersection: Common Elements
Intersection keeps only elements that exist in both sets:
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // Set { 2, 3 }
Difference: Elements in A but Not B
Difference returns elements from the first set that aren't in the second:
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // Set { 1 }
Why This Matters
These patterns let you efficiently compare and manipulate collections of unique values—perfect for filtering duplicate data, finding commonalities, or removing unwanted elements.
Key Takeaway: Use spread + Set constructor for union, convert to array + filter() + has() for intersection, and add ! to has() for difference operations.