How to Get the Union of Two Arrays or Sets in JavaScript
In data manipulation, a "union" of two collections is a new collection that contains all the unique elements from both original sets. This is a common task when you need to merge two lists without having any duplicate entries in the final result. The Set object in JavaScript is the perfect tool for this job.
This guide will teach you the modern, idiomatic method for getting the union of two arrays and two Set objects, leveraging the unique properties of the Set data structure.
The Core Concept: Using a Set for Uniqueness
The Set object is a collection of values where each value must be unique. When you create a Set from an iterable (like an array) that contains duplicates, the duplicates are automatically discarded. This feature makes it the ideal tool for creating a union.
const arrayWithDuplicates = ['a', 'b', 'a', 'c'];
const uniqueSet = new Set(arrayWithDuplicates);
console.log(uniqueSet); // #
Output:
Set(3) { 'a', 'b', 'c' }
How to Get the Union of Two Arrays
The most concise and readable way to get the union of two arrays is to merge them and then use a Set to handle deduplication.
For example, you have two arrays and you want a new array with all the unique values from both.
// Problem: How to get a single array with all unique letters?
const arrayA = ['a', 'b', 'c'];
const arrayB = ['c', 'd', 'e'];
This clean, one-line solution is the best practice.
const arrayA = ['a', 'b', 'c'];
const arrayB = ['c', 'd', 'e'];
// 1. Merge both arrays into a single array using the spread syntax (...)
// -> ['a', 'b', 'c', 'c', 'd', 'e']
// 2. Create a new Set from the merged array to remove duplicates
// -> Set { 'a', 'b', 'c', 'd', 'e' }
// 3. Convert the Set back to an array
const union = [...new Set([...arrayA, ...arrayB])];
console.log(union);
Output:
['a', 'b', 'c', 'd', 'e']
An alternative to the final spread syntax is Array.from(mySet).
How to Get the Union of Two Sets
Getting the union of two Set objects is even more direct, as you are already working with Sets.
For example, we want the union of these two sets A and B:
const setA = new Set(['a', 'b', 'c']);
const setB = new Set(['c', 'd', 'e']);
The logic is the same as with arrays: merge the iterables and let the Set constructor handle the deduplication.
const setA = new Set(['a', 'b', 'c']);
const setB = new Set(['c', 'd', 'e']);
const union = new Set([...setA, ...setB]);
console.log(union);
Output:
Set(5) { 'a', 'b', 'c', 'd', 'e' }
This is the most efficient and idiomatic way to get the union of two or more Sets.
Why the Set Method is the Best Practice
While you could achieve a union with other array methods like filter() and concat(), that approach is more complex and less performant.
The manual filter() method is more verbose:
const arrayA = ['a', 'b', 'c'];
const arrayB = ['c', 'd', 'e'];
// Find elements in B that are not in A
const uniqueInB = arrayB.filter(element => !arrayA.includes(element));
// Combine A with the unique elements from B
const union = [...arrayA, ...uniqueInB];
Output:
['a', 'b', 'c', 'd', 'e']
The Set method is superior because it is:
- More Declarative:
new Set([...a, ...b])clearly communicates that you are creating a unique collection from two sources. - More Performant: Creating a
Setand iterating is generally faster than usingfilter()withincludes()inside a loop, especially for large arrays. - Simpler: The logic is straightforward and less prone to off-by-one errors.
Conclusion
For creating a union of arrays or Sets, the Set object is the definitive best practice in modern JavaScript.
- To get the union of two arrays, merge them and convert to a
Setand back to an array:[...new Set([...arrayA, ...arrayB])]. - To get the union of two
Sets, merge them into a newSet:new Set([...setA, ...setB]).
This functional approach is clean, readable, and leverages the native capabilities of JavaScript's data structures for an efficient and elegant solution.