0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Union of Two Arrays

You can find the union of two arrays in JavaScript by combining them and using new Set([...arr1, ...arr2]) to remove duplicates, then converting back to an array with Array.from().
📋

Examples

Input[1, 2, 3], [3, 4, 5]
Output[1, 2, 3, 4, 5]
Input["apple", "banana"], ["banana", "cherry"]
Output["apple", "banana", "cherry"]
Input[], [1, 2]
Output[1, 2]
🧠

How to Think About It

To find the union of two arrays, think of putting all elements from both arrays into one big collection. Then, remove any repeated items so each element appears only once. This is like mixing two baskets of fruits and keeping only one of each fruit type.
📐

Algorithm

1
Take the first array and the second array as input.
2
Combine both arrays into one larger array.
3
Remove duplicate elements from the combined array.
4
Return the array with unique elements as the union.
💻

Code

javascript
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);
Output
[1, 2, 3, 4, 5]
🔍

Dry Run

Let's trace the example arrays [1, 2, 3] and [3, 4, 5] through the code.

1

Combine arrays

Combine [1, 2, 3] and [3, 4, 5] into [1, 2, 3, 3, 4, 5]

2

Create Set to remove duplicates

Create new Set from [1, 2, 3, 3, 4, 5] which becomes {1, 2, 3, 4, 5}

3

Convert Set back to array

Convert {1, 2, 3, 4, 5} to [1, 2, 3, 4, 5]

StepCombined ArraySet ContentFinal 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

Using filter and indexOf
javascript
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]));
This method uses <code>filter</code> and <code>indexOf</code> to keep only the first occurrence of each element but is less efficient for large arrays.
Using a for loop and object keys
javascript
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]));
This approach uses an object to track seen elements and works well but only for primitive types.

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.

ApproachTimeSpaceBest For
Set with spread operatorO(n + m)O(n + m)Clean and efficient for all data types
Filter with indexOfO((n + m)^2)O(n + m)Simple but slow for large arrays
Object keys trackingO(n + m)O(n + m)Fast but only for primitive types
💡
Use the Set object to easily remove duplicates when combining arrays for union.
⚠️
Forgetting to remove duplicates after combining arrays, which results in repeated elements in the union.