JavaScript Program to Find Union of Two Arrays
new Set([...arr1, ...arr2]) to remove duplicates, then converting back to an array with Array.from().Examples
How to Think About It
Algorithm
Code
const union = (arr1, arr2) => Array.from(new Set([...arr1, ...arr2])); const array1 = [1, 2, 3]; const array2 = [3, 4, 5]; const result = union(array1, array2); console.log(result);
Dry Run
Let's trace the example arrays [1, 2, 3] and [3, 4, 5] through the code.
Combine arrays
Combine [1, 2, 3] and [3, 4, 5] into [1, 2, 3, 3, 4, 5]
Create Set to remove duplicates
Create new Set from [1, 2, 3, 3, 4, 5] which becomes {1, 2, 3, 4, 5}
Convert Set back to array
Convert {1, 2, 3, 4, 5} to [1, 2, 3, 4, 5]
| Step | Combined Array | Set Content | Final Array |
|---|---|---|---|
| 1 | [1, 2, 3, 3, 4, 5] | ||
| 2 | {1, 2, 3, 4, 5} | ||
| 3 | [1, 2, 3, 4, 5] |
Why This Works
Step 1: Combine arrays
Using the spread operator ..., we join both arrays into one big array containing all elements.
Step 2: Remove duplicates with Set
A Set automatically removes duplicate values, so converting the combined array to a Set keeps only unique elements.
Step 3: Convert Set back to array
Since a Set is not an array, we use Array.from() to convert it back to a normal array for easy use.
Alternative Approaches
function union(arr1, arr2) { const combined = arr1.concat(arr2); return combined.filter((item, index) => combined.indexOf(item) === index); } console.log(union([1,2,3], [3,4,5]));
function union(arr1, arr2) { const obj = {}; const result = []; for (const item of arr1.concat(arr2)) { if (!obj.hasOwnProperty(item)) { obj[item] = true; result.push(item); } } return result; } console.log(union([1,2,3], [3,4,5]));
Complexity: O(n + m) time, O(n + m) space
Time Complexity
Combining two arrays takes O(n + m) time, and creating a Set to remove duplicates also takes O(n + m), so total time is O(n + m).
Space Complexity
The new Set and resulting array require extra space proportional to the total number of unique elements, so O(n + m).
Which Approach is Fastest?
Using Set is generally faster and cleaner than filter/indexOf or object tracking, especially for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set with spread operator | O(n + m) | O(n + m) | Clean and efficient for all data types |
| Filter with indexOf | O((n + m)^2) | O(n + m) | Simple but slow for large arrays |
| Object keys tracking | O(n + m) | O(n + m) | Fast but only for primitive types |