JavaScript Set Operations
JavaScript Sets store unique values, which makes them ideal for mathematical set operations. Although JavaScript doesn’t provide built-in methods for union or intersection, we can achieve them using spread operators, loops, or helper functions.
1. Union
Combine all unique elements from two sets.
function union(setA, setB) {
return new Set([...setA, ...setB]);
}
const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
console.log(union(a, b)); // Set {1, 2, 3, 4, 5}
2. Intersection
Get elements common to both sets.
function intersection(setA, setB) {
return new Set([...setA].filter(x => setB.has(x)));
}
console.log(intersection(a, b)); // Set {3}
3. Difference
Elements in the first set but not in the second.
function difference(setA, setB) {
return new Set([...setA].filter(x => !setB.has(x)));
}
console.log(difference(a, b)); // Set {1, 2}
4. Symmetric Difference
Elements in either set, but not in both.
function symmetricDifference(setA, setB) {
return new Set([...difference(setA, setB), ...difference(setB, setA)]);
}
console.log(symmetricDifference(a, b)); // Set {1, 2, 4, 5}
5. Subset
Check if all elements of one set exist in another.
function isSubsetOf(setA, setB) {
return [...setA].every(x => setB.has(x));
}
const c = new Set([1, 2]);
console.log(isSubsetOf(c, a)); // true
6. Superset
Check if a set contains all elements of another set.
function isSupersetOf(setA, setB) {
return [...setB].every(x => setA.has(x));
}
console.log(isSupersetOf(a, c)); // true
7. Disjoint
Check if two sets have no elements in common.
function isDisjointFrom(setA, setB) {
return ![...setA].some(x => setB.has(x));
}
const d = new Set([6, 7]);
console.log(isDisjointFrom(a, d)); // true
console.log(isDisjointFrom(a, b)); // false
Summary Table
Operation | Description | Example |
---|---|---|
union | Combine all unique elements | {1,2,3} ∪ {3,4} = {1,2,3,4} |
intersection | Common elements | {1,2,3} ∩ {2,3} = {2,3} |
difference | In first but not second | {1,2,3} - {2,3} = {1} |
symmetricDifference | Elements in either, not both | {1,2} Δ {2,3} = {1,3} |
isSubsetOf | All elements of A in B | {1,2} ⊆ {1,2,3} = true |
isSupersetOf | All elements of B in A | {1,2,3} ⊇ {1,2} = true |
isDisjointFrom | No common elements | {1,2} ∩ {3,4} = ∅ |