JS Set Logic
In this page:
const union = new Set([...setA, ...setB]);
const intersection = new Set([...setA].filter(x => setB.has(x)));
const difference = new Set([...setA].filter(x => !setB.has(x)));
Union: Combining Two Sets
setA.union(setB) returns a brand-new Set containing every unique item from both Sets combined -- exactly like merging two lists together while automatically discarding any duplicates, since a Set can never hold the same value twice.
उदाहरण: Union: Combining Two Sets
const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
console.log(a.union(b)); // {1, 2, 3, 4, 5}
Intersection: Finding Shared Items
setA.intersection(setB) returns a new Set containing only the items present in BOTH Sets -- useful for finding common elements, like tags shared between two articles, or users who appear in two separate groups.
उदाहरण: Intersection: Finding Shared Items
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log(a.intersection(b)); // {2, 3}
Difference: Finding What's Unique to One Set
setA.difference(setB) returns a new Set containing only the items present in setA but NOT in setB -- useful for finding what has been removed, what remains to be processed, or what one group has that another does not, in one direction only.
उदाहरण: Difference: Finding What's Unique to One Set
const a = new Set([1, 2, 3]);
const b = new Set([2, 3]);
console.log(a.difference(b)); // {1}
Other Set Relationship Checks
isSubsetOf(), isSupersetOf(), and isDisjointFrom() answer specific yes/no questions about how two Sets relate -- whether one is entirely contained within the other, whether one entirely contains the other, or whether they share no elements at all.
उदाहरण: Other Set Relationship Checks
const a = new Set([1, 2]);
const b = new Set([1, 2, 3]);
console.log(a.isSubsetOf(b)); // true
console.log(b.isSupersetOf(a)); // true
console.log(a.isDisjointFrom(new Set([9]))); // true
Fallback for Older Browsers
Since these set-operation methods are a relatively recent addition, code needing to support older browsers can achieve the same results with array methods and manual filtering -- combining spread syntax with .filter() to replicate union, intersection, and difference behavior manually.
उदाहरण: Fallback for Older Browsers
const a = [1, 2, 3];
const b = [2, 3, 4];
const union = [...new Set([...a, ...b])];
const intersection = a.filter(x => b.includes(x));
console.log(union, intersection); // manual fallback for older browsers
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS Dates
- JS Math
- JS Conditionals
- JS Switch
- JS Loop For
- JS Loop While
- JS Iterables
- JS Sets
- JS Maps
- JS typeof
- JS Type Conversion
- JS Destructuring
- JS Arrow Functions
- JS Classes
- JS Modules
- JS Promises
- JS Async/Await
- JS DOM
- JS DOM Methods
- JS Events Advanced
- JS DOM Navigation
- JS DOM Collections
- JS Async Callbacks
- JS Async Parallel
- JS Date Set
- JS Set Logic