How To Get The Union Of Two Arrays In JavaScript?

When working with arrays, we sometimes come across two arrays containing some of the same elements. So today, we will show you how to get the union of two arrays in JavaScript.

How to get the union of two arrays in JavaScript?

Using concat(), For … of, and set constructor

We have already introduced you to the syntax of the concat() function in this article. You can find it in the “Merge two arrays in JS” section.

First, we will use the concat() function to join two arrays. Then we initialize a set from the newly created array to get a set with duplicates removed. Finally, we’ll use the for ... of to convert a set to an array by pushing all the set’s elements into an empty array we created earlier. See the example below for a better understanding:

const array1 = ['Learn', 'Share', 'IT'];
const array2 = ['Learn', 'Share', 'Knowledge'];

// Concat 2 arrays together
const concatenatedArray = array1.concat(array2);

// Create a set to eliminate duplicates
const set = new Set(concatenatedArray);

// Array that holds the Union
const unionArr = [];

// Iterate & push set element into Union Array
for(let element of set) {
unionArr.push(element);
}

console.log(unionArr);

Output:

[ 'Learn', 'Share', 'IT', 'Knowledge' ]

This way, we will use the Spread Operator instead of the loop. We also introduced the Spread operator in previous posts. You can read it here.

Next, continue to use the Spread Operator to expand the set created by the merged array above. Finally, put it all into an array. Like this:

const array1 = ['Learn', 'Share', 'IT'];
const array2 = ['Learn', 'Share', 'Knowledge'];

// Concat 2 arrays together
const concatenatedArray = [...array1, ...array2];

// Expand the set using Spread, and remove duplicates using the Set() constructor.
const unionArr = [...new Set(concatenatedArray)];

console.log(unionArr);

Output:

[ 'Learn', 'Share', 'IT', 'Knowledge' ]

Using _.union() function in Underscore.js

Underscore.js provides many valuable functions that work with arrays and objects.

The _.union() function takes multiple arrays and returns a union of all arrays.

Syntax:

_.union(arr1, arr2, arr3, ...)

Parameters:

• arr1, arr2, arr3, …: arrays want to combine.

Before using _.union(), please import the Underscore.js helper library using the CDN here.

To get union with the _.union() is very simple, just pass 2 arrays to _.union() function. Like this example:

const array1 = ["Learn", "Share", "IT"];
const array2 = ["Learn", "Share", "Knowledge"];

// Use _.union() to get the Union of 2 arrays
const unionArr = _.union(array1, array2);

console.log(unionArr);

Output:

['Learn', 'Share', 'IT', 'Knowledge']

Summary

Congratulations! you already know how to get the union of two arrays in JavaScript. We hope this article helps you on your way to becoming a JavaScript developer.

Have a beautiful day!

Maybe you are interested: