How to get the Union of Two Arrays in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 17 20212 min read

Get the Union of Two Arrays in JavaScript #

To get a union of two arrays:

  1. Use the spread operator (...) to merge the arrays into a third array.
  2. Pass the third array as a parameter to the Set constructor to remove the duplicates.
  3. Convert the Set back to an array.
index.js
const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c', 'd']; const union = Array.from(new Set([...arr1, ...arr2])); // ๐Ÿ‘‡๏ธ ['a', 'b', 'c', 'd'] console.log(union);

We used the Set object to remove all the duplicates from the two arrays.

The Set object allows us to store unique values and removes all duplicates automatically.

If we pass it an array containing the same value multiple times, it would only get added once to the Set.

index.js
console.log(new Set(['a', 'a', 'a'])); // ๐Ÿ‘‰๏ธ { 'a' }

We also use the spread operator (...) to unpack the values of the two arrays into a third array.

The last step is to convert the set back to an array, using the Array.from method.

Here's an alternative, but more complicated approach.

To get a union of two arrays:

  1. Get the elements that are contained in the first array and not contained in the second
  2. Merge them with the elements of the second array
index.js
const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c', 'd']; function getUnion(array1, array2) { const difference = array1.filter( element => !array2.includes(element) ); return [...difference, ...array2]; } // ๐Ÿ‘‡๏ธ ['a', 'b', 'c', 'd'] console.log(getUnion(arr1, arr2));

We use the filter method to iterate over the first array and get a new array containing only the elements that are present in the first and absent in the second array.

The last step is to merge the difference with the values from the second array.

This approach is not as direct and intuitive as leveraging the Setfunctionality to remove the duplicates, I would definitely pick the first approach.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee