JavaScript Set Logic

JavaScript Tutorial

JavaScript Set Logic

JavaScript Set Logic can be used to perform mathematical set operations such as:

  • Union

  • Intersection

  • Difference

  • Subset Check

These are useful in algorithms, data filtering, search operations, and comparisons.


Union (Combine Two Sets)

Union = All unique elements from both sets


 

Output:

Set { 1, 2, 3, 4, 5 }

 Intersection (Common Elements)

Intersection = Elements present in both sets

Output:

Set { 3 }

 Difference (Elements in A but not in B)

Output:

Set { 1, 2 }

 Symmetric Difference (Elements NOT in both)

Elements unique to either set, but not shared.


 

console.log(symmetricDifference);

Output:

Set { 1, 2, 4, 5 }

 Subset Check (Is A a subset of B?)

Example:

let smallSet = new Set([1, 2]);
let bigSet = new Set([1, 2, 3, 4]);
console.log([…smallSet].every(v => bigSet.has(v))); // true

 Bonus: Superset Check


 Summary Table

OperationResult Example
Union{1,2,3} + {3,4}{1,2,3,4}
Intersection{1,2,3} ∩ {2,3,4}{2,3}
Difference{1,2,3} - {2,3}{1}
Symmetric DifferenceUnique in both → {1,4}
Subset Check{1,2}{1,2,3}true

Practical Use Example: Finding Unique Users


 

You may also like...