How to get the Union of Two Sets in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20212 min read

banner

Photo by Max Vertsanov

Get the Union of Two Sets in JavaScript #

To get a union of two Sets, use the spread syntax (...) to unpack the values of the Sets into an array and pass the result to the Set() constructor, e.g. new Set([...set1, ...set2]). 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'}

We used the spread syntax (...) to unpack the values from 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.

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

Get a Union of Two Sets using for of loop #

To get a union of two Sets, pass the first Set to the Set() constructor to create a third Set. Then use the for...of loop to iterate over the second Set and add each element to the newly created Set. The new Set will contain a union of the other two Sets.

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'}

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

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

Then, we used the for...of loop to iterate over the second Set and add its values to the new Set.

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

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