How to compute union of JavaScript arrays?

We can get the union of two arrays by merging both arrays and removing duplicate elements, and the union gives unique elements from both arrays.

In this tutorial, we will learn to compute the union of JavaScript arrays using various approaches.

Use the set() Data Structure

The first approach is using the set() data structure. The set data structure can contain only unique elements. We can add all elements of both arrays into the set and create a new array from the setâ€™s elements to create a union.

Syntax

Users can follow the syntax below to compute the union of JavaScript arrays using the set data structure.

let union = [...new Set([...array1, ...array2])];

In the above syntax, we have used the spread operator concat both arrays and created a new set from the resultant array. After that, we used the spread operator again to add elements of the set into the array.

Example 1

In the example below, array1 and array2 contain some common numbers. First, we contacted array1 and array2 using the spread operator. After that, we used the new Set() constructor to create a set from the resultant array. The set can have only unique elements. So, it contains all elements in the union of both arrays.

After that, we add all elements of the set to the union array using the spread operator. In the output, users can observe the union of both arrays.

<html>
<body>
<h3> Using the <i> set() </i> data structure to compute the union of two arrays in JavaScript </h3>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');

// using the set() to compute union
let array1 = [1, 2, 3, 4, 5];
let array2 = [4, 5, 6, 7, 8];
let union = [...new Set([...array1, ...array2])];
output.innerHTML = "The first array is " + array1 + "<br>";
output.innerHTML += "The second array is " + array2 + "<br>";
output.innerHTML += "The union of the two arrays is " + union + "<br>";
</script>
</body>
</html>

Using the Object to Compute Union of JavaScript Arrays

In this approach, we can add array values as object properties. The object always contains unique keys. So, we can use both array elements as a key of the object and any value for that particular key. After that, we can fetch all object keys to get the array's union.

Syntax

Users can follow the syntax below to use the object to compute the union of arrays.

for () {
union[names1[i]] = 1;
}
for (let key in the union) {
finalArray.push(key);
}

In the above syntax, first, we push all array elements as a key of the object. After that, we fetch keys from the object and add them to the array.

Example 2

In the example below, We have two arrays named names1 and names2. We added the elements of the first array as a key of the object. After that, we added the elements of the second array as a key of the object.

Next, we iterate through the object, get the keys of the object and push to the finalArray. The finalArray contains the union of the names1 and names2 arrays.

<html>
<body>
<h3> Using the <i> object </i> to compute the union of two arrays in JavaScript </h3>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');

// using the object to compute the union of two arrays
let names1 = ["John", "Peter", "Sally", "Jane", "Mark"];
let names2 = ["Peter", "Sally", "Greg"];
let union = {};

//Add all the elements of the first array to the object
for (let i = 0; i < names1.length; i++) {
union[names1[i]] = 1;
}
for (let i = 0; i < names2.length; i++) {
union[names2[i]] = 1;
}

//Convert the object to an array
let finalArray = [];
for (let key in union) {
finalArray.push(key);
}
output.innerHTML = "First array: " + JSON.stringify(names1) + "<br>";
output.innerHTML += "Second array: " + JSON.stringify(names2) + "<br>";
output.innerHTML += "The union of the two arrays: " + JSON.stringify(finalArray) + "<br>";
</script>
</body>
</html>

Use the Filter() and Concat() Method

The concat() method is used to merge two or more arrays. We can filter the unique elements after merging both arrays using the filter() method. In this way, we can compute the union of arrays using the concat() and filter() methods.

Syntax

Users can follow the syntax below to use the filter() and concat() methods to compute the union of the array.

let cities = cities1.concat(cities2);
cities.sort();
let unionCities = cities.filter((value, index) => cities.indexOf(value) === index);

In the above syntax, we first merged both arrays, sorted them, and filtered unique elements using the filter() method.

Example 3

In the example below, the cities1 and citites2 array contains some city names, and some of them are common. The cities array contains the array elements of both the array.

After that, we sort the cities array using the sort() method. Next, we use the filter() method to filter unique values from the cities array. In the filter() method, we pass the callback function as a parameter, which checks the index of the current city is equal to the current index to remove the duplicate elements.

<html>
<body>
<h3> Using the <i> filter() and concat() methods </i> to compute the union of two arrays in JavaScript </h3>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
let cities2 = ["Mumbai", "Pune", "Nagpur", "Nashik", "Rajkot"];
let cities = cities1.concat(cities2);
cities.sort();

// filter unique values in the array
let unionCities = cities.filter((value, index) => cities.indexOf(value) === index);
output.innerHTML = "First array: " + JSON.stringify(cities1) + "<br>";
output.innerHTML += "Second array: " + JSON.stringify(cities2) + "<br>";
output.innerHTML += "The union of the two arrays: " + JSON.stringify(unionCities) + "<br>";
</script>
</body>
</html>

Conclusion

Users learned three different approaches to computing the union of arrays in JavaScript. The first approach requires one linear code using the set data structure. The second approach uses the object, and the third uses the filter() and concat() methods.

Updated on: 19-Apr-2023

199 Views