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
Adding two Sets in Javascript
The operation of adding 2 sets is known as a union. You need to add every element from one set to another while checking for duplicates. JavaScript's built-in Set class doesn't include a union method, but we can implement it using several approaches.
Method 1: Using Spread Operator (Recommended)
The most concise way to combine two sets is using the spread operator:
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([2, 3, 5, 6]);
// Create union using spread operator
let unionSet = new Set([...setA, ...setB]);
console.log(unionSet);
console.log("Size:", unionSet.size);
Set(5) { 1, 2, 3, 4, 5, 6 }
Size: 6
Method 2: Using forEach to Add Elements
You can also create a union by iterating through one set and adding elements to another:
let setA = new Set([1, 2, 3]); let setB = new Set([3, 4, 5]); // Create new set starting with setA let unionSet = new Set(setA); // Add all elements from setB setB.forEach(elem => unionSet.add(elem)); console.log(unionSet);
Set(5) { 1, 2, 3, 4, 5 }
Method 3: Custom Static Union Function
You can extend the Set prototype or create a utility function:
Set.union = function(setA, setB) {
if (!(setA instanceof Set) || !(setB instanceof Set)) {
throw new Error("Both arguments must be Set instances");
}
return new Set([...setA, ...setB]);
};
let setA = new Set([1, 2, 3, 4]);
let setB = new Set([2, 3, 5, 6]);
let result = Set.union(setA, setB);
console.log(result);
Set(6) { 1, 2, 3, 4, 5, 6 }
Comparison
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
| Spread Operator | Fast | Excellent | Efficient |
| forEach | Good | Good | Efficient |
| Custom Function | Fast | Excellent | Efficient |
Key Points
- Sets automatically handle duplicates - duplicate elements are ignored
- The spread operator method is the most concise and readable
- Union operations create new sets without modifying originals
- Order of elements follows insertion order in the union
Conclusion
Use the spread operator approach for combining sets in JavaScript. It's concise, efficient, and automatically handles duplicates while preserving the immutability of original sets.
Advertisements
