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
Finding union of two sets in JavaScript
The union of two sets is the combination of all unique elements from both sets. In JavaScript, we can find the union of two arrays using several approaches.
What is Union Set
Union Set is the set made by combining the elements of two sets. Therefore, the union of sets A and B is the set of elements in A, or B, or both.
For example ?
If we have two sets denoted by two arrays like this ?
const arr1 = [1, 2, 3]; const arr2 = [100, 2, 1, 10];
Then the union set will be ?
[1, 2, 3, 10, 100]
Using Set and Spread Operator (Modern Approach)
The simplest way to find union is using the Set constructor to remove duplicates:
const arr1 = [1, 2, 3];
const arr2 = [100, 2, 1, 10];
const findUnion = (arr1, arr2) => {
return [...new Set([...arr1, ...arr2])];
};
console.log(findUnion(arr1, arr2));
[ 1, 2, 3, 100, 10 ]
Using Object Map (Traditional Approach)
Using an object to track unique elements:
const arr1 = [1, 2, 3];
const arr2 = [100, 2, 1, 10];
const findUnion = (arr1 = [], arr2 = []) => {
const map = {};
const res = [];
for (let i = arr1.length - 1; i >= 0; --i) {
map[arr1[i]] = arr1[i];
}
for (let i = arr2.length - 1; i >= 0; --i) {
map[arr2[i]] = arr2[i];
}
for (const n in map) {
if (map.hasOwnProperty(n)) {
res.push(map[n]);
}
}
return res;
};
console.log(findUnion(arr1, arr2));
[ 1, 2, 3, 10, 100 ]
Using filter() and includes()
Another approach using array methods:
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
const findUnion = (arr1, arr2) => {
const uniqueFromArr2 = arr2.filter(item => !arr1.includes(item));
return [...arr1, ...uniqueFromArr2];
};
console.log(findUnion(arr1, arr2));
[ 1, 2, 3, 4, 5, 6 ]
Comparison
| Method | Time Complexity | Readability | Best For |
|---|---|---|---|
| Set + Spread | O(n + m) | High | Modern JavaScript |
| Object Map | O(n + m) | Medium | Older browsers |
| filter + includes | O(n * m) | High | Small arrays |
Conclusion
The Set with spread operator provides the cleanest and most efficient solution for finding union of arrays. Use the object map approach for older JavaScript environments where Set is not available.
