Get the Union of Two Arrays or Sets in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
6 min

banner

# Table of Contents

  1. Get the Union of Two Arrays in JavaScript
  2. Get the Union of Two Sets in JavaScript

# Get the Union of Two Arrays in JavaScript

To get a union of two arrays:

  1. Use the spread syntax (...) 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);

get union of two arrays

The code for this article is available on GitHub
The union of two Set objects is the smallest Set which contains all the elements of both Set objects.

We used the Set() constructor to remove all of the duplicates from the two arrays.

Set objects only store unique values, so all of the duplicates get automatically removed.

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

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

We used the spread syntax (...) to unpack the values of the two arrays into a third 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);

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

You can also use the spread syntax (...) to convert the Set object to an array, but it makes the code more difficult to read.

index.js
const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c', 'd']; const union = [...new Set([...arr1, ...arr2])]; // ๐Ÿ‘‡๏ธ ['a', 'b', 'c', 'd'] console.log(union);

Alternatively, you can use the Array.filter() method.

# Get the Union of Two Arrays using Array.filter()

This is a two-step process:

  1. Get the elements that are contained in the first array and not contained in the second array.
  2. Merge the result 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));

get union of two arrays using array filter

The code for this article is available on GitHub

We used the Array.filter() method to iterate over the first array.

On each iteration, we check if the current element is not contained in the second array.

The output of the filter() method is a new array that contains the elements of the first array that aren't in the second array.

index.js
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f']; const arr2 = ['a', 'b', 'c', 'd']; const difference = arr1.filter(element => !arr2.includes(element)); console.log(difference); // ๐Ÿ‘‰๏ธ [ 'e', 'f' ]

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

index.js
function getUnion(array1, array2) { const difference = array1.filter(element => !array2.includes(element)); return [...difference, ...array2]; } const arr1 = ['a', 'b', 'c', 'd', 'e', 'f']; const arr2 = ['a', 'b', 'c', 'd']; // ๐Ÿ‘‡๏ธ [ 'e', 'f', 'a', 'b', 'c', 'd' ] console.log(getUnion(arr1, arr2));

This approach is not as direct and intuitive as leveraging the Set functionality to remove the duplicates.

# Get the Union of Two or more Arrays using lodash

Alternatively, you can use the lodash library.

  1. Install the lodash library.
shell
npm install lodash # ๐Ÿ‘‡๏ธ only if you use TypeScript npm install @types/lodash --save-dev
  1. Use the union() method to get the union of two or more arrays.
index.js
import _ from 'lodash'; const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = ['a', 'e', 'f']; const union = _.union(arr1, arr2); // ๐Ÿ‘‡๏ธ [ 'a', 'b', 'c', 'd', 'e', 'f' ] console.log(union);

get union of two or more arrays using lodash

The code for this article is available on GitHub

The union() method creates an array of unique values, in order, from all of the provided arrays.

You can also use the union() method to get the union of more than two arrays.

index.js
import _ from 'lodash'; const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = ['a', 'e', 'f']; const arr3 = ['e', 'y']; const union = _.union(arr1, arr2, arr3); // ๐Ÿ‘‡๏ธ [ // 'a', 'b', 'c', // 'd', 'e', 'f', // 'y' // ] console.log(union);

We passed 3 arrays to the union() method and it returned the union of the arrays.

# Get the Union of Two Sets in JavaScript

To get a union of two Set objects:

  1. Use the spread syntax (...) to unpack the values of the Sets into an array.
  2. Pass the result to the Set() constructor.
  3. The new Set will contain the union of the other two.
index.js
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const union = new Set([...set1, ...set2]); console.log(union); // ๐Ÿ‘‰๏ธ {'a', 'b', 'c', 'd'}

get union of two sets

The code for this article is available on GitHub

We used the spread syntax (...) to unpack the values of the two Set objects into an array.

index.js
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const arr = [...set1, ...set2]; console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c' ,'a', 'b', 'd']

The array stores duplicate values as opposed to a Set. Once the array is passed to the Set() constructor, all of the duplicates are ignored.

index.js
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const union = new Set([...set1, ...set2]); console.log(union); // ๐Ÿ‘‰๏ธ {'a', 'b', 'c', 'd'}

The Set() constructor takes an iterable object as a parameter, so an array is perfect.

You can use this approach to get the union of more than two Set objects.

index.js
const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); const set3 = new Set(['a', 'b', 'e']); const union = new Set([...set1, ...set2, ...set3]); console.log(union); // ๐Ÿ‘‰๏ธ Set(5) { 'a', 'b', 'c', 'd', 'e' }

You can unpack as many Set objects as necessary in the call to the Set() constructor.

# Get a Union of Two Sets using a for...of loop

This is a four-step process:

  1. Pass the first Set to the Set() constructor to create a third Set.
  2. Use a for...of loop to iterate over the second Set.
  3. Add each element to the newly created Set.
  4. The new Set will contain the union of the other two.
index.js
function getUnion(setA, setB) { const union = new Set(setA); for (const element of setB) { union.add(element); } return union; } const set1 = new Set(['a', 'b', 'c']); const set2 = new Set(['a', 'b', 'd']); console.log(getUnion(set1, set2)); // ๐Ÿ‘‰๏ธ {'a', 'b', 'c', 'd'}
The code for this article is available on GitHub

We created a reusable function that returns the union of two Sets.

The first step is to create a new Set from the first Set.

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

On each iteration, we use the Set.add() method to add the current element to the new Set.

The Set.add() method inserts a new element with the supplied value into a Set object, if the value is not already in the Set.

Sets don't store duplicate values, so we don't have to worry about handling that.

# Getting a Union of two sets with the Set.union() method

There is also a newer Set.union() method, however, it doesn't have good browser or server compatibility.

At the time of writing the method is not supported in Firefox and Node.js.

Here is an example of how you can use the method in the browser with a core-js polyfill.

index.js
import 'https://cdn.jsdelivr.net/npm/core-js@3.36.0/actual/set/index.js/+esm'; const a = new Set(['a', 'b', 'c']); const b = new Set(['x', 'y', 'a']); // ๐Ÿ‘‡๏ธ { "a", "b", "c", "x", "y" } console.log(a.union(b));

The Set.union() method takes a Set and returns a new Set containing the elements that are in either or both Set objects.

You can read more about the method and check its browser compatibility table in this section of the MDN docs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev