JavaScript Set Logic

JavaScript Set Logic

Sets 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.


1️⃣ Union (Combine Two Sets)

Union = All unique elements from both sets


 

Output:

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

2️⃣ Intersection (Common Elements)

Intersection = Elements present in both sets



 

Output:

Set { 3 }

3️⃣ Difference (Elements in A but not in B)



 

Output:

Set { 1, 2 }

4️⃣ Symmetric Difference (Elements NOT in both)

Elements unique to either set, but not shared.


 

console.log(symmetricDifference);

Output:

Set { 1, 2, 4, 5 }

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

Operation Result 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 Difference Unique in both → {1,4}
Subset Check {1,2}{1,2,3}true

✔ Practical Use Example: Finding Unique Users


 

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *