Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Subtract two Sets in Javascript
Set subtraction (difference) removes all elements from the first set that exist in the second set. JavaScript doesn't provide a built-in difference method, but we can create one using forEach or modern Set methods.
Using forEach Method
We can create a static method to subtract one Set from another:
Set.difference = function(s1, s2) {
if (!(s1 instanceof Set) || !(s2 instanceof Set)) {
console.log("The given objects are not of type Set");
return null;
}
let newSet = new Set();
s1.forEach(elem => newSet.add(elem));
s2.forEach(elem => newSet.delete(elem));
return newSet;
}
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([2, 3]);
console.log(Set.difference(setA, setB));
Set { 1, 4 }
Using Filter and Spread Operator (Modern Approach)
A more concise approach using array methods:
function setDifference(setA, setB) {
return new Set([...setA].filter(x => !setB.has(x)));
}
let set1 = new Set([1, 2, 3, 4, 5]);
let set2 = new Set([3, 4, 6, 7]);
let difference = setDifference(set1, set2);
console.log("Set1:", set1);
console.log("Set2:", set2);
console.log("Difference (Set1 - Set2):", difference);
Set1: Set { 1, 2, 3, 4, 5 }
Set2: Set { 3, 4, 6, 7 }
Difference (Set1 - Set2): Set { 1, 2, 5 }
Adding to Set Prototype
You can add the difference method directly to the Set prototype:
Set.prototype.difference = function(otherSet) {
return new Set([...this].filter(x => !otherSet.has(x)));
};
let fruits = new Set(['apple', 'banana', 'orange']);
let citrus = new Set(['orange', 'lemon', 'lime']);
console.log("All fruits:", fruits);
console.log("Citrus fruits:", citrus);
console.log("Non-citrus fruits:", fruits.difference(citrus));
All fruits: Set { 'apple', 'banana', 'orange' }
Citrus fruits: Set { 'orange', 'lemon', 'lime' }
Non-citrus fruits: Set { 'apple', 'banana' }
Comparison of Methods
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| forEach | Good | Good | ES6+ |
| Filter + Spread | Moderate | Excellent | ES6+ |
| Prototype method | Good | Excellent | ES6+ |
Conclusion
Set subtraction removes common elements from the first set. The filter method with spread operator provides the most readable solution, while forEach offers better performance for large sets.
Advertisements
