How to merge Sets using JavaScript


Borislav Hadzhiev

Last updated: Aug 30, 2022


Photo from Unsplash

Merge Set Objects using JavaScript #

To merge Sets, use the spread operator (...) to unpack the values of two or more Sets into an array and pass them into the Set() constructor, e.g. new Set([...set1, ...set2]). The new Set will contain all of the elements from the provided Set objects.

const set1 = new Set(['one', 'two']); const set2 = new Set(['three']); const set3 = new Set([...set1, ...set2]); console.log(set3); // 👉️ {'one', 'two', 'three'}

We used the spread operator (...) to unpack the elements from 2 Set objects into an array.

const set1 = new Set(['one', 'two']); console.log([...set1]); // 👉️ ['one', 'two']

The last step is to pass the array to the Set() constructor, which takes an iterable as a parameter.

With the values in place, the new Set looks as follows.

const set3 = new Set(['one', 'two', 'three']);

This process could be repeated with as many Set objects as necessary.

const set1 = new Set(['one']); const set2 = new Set(['two']); const set3 = new Set(['three']); const set4 = new Set([...set1, ...set2, ...set3]); console.log(set4); // 👉️ {'one', 'two', 'three'}
Methods like forEach iterate over the Set object in element insertion order. If you need to change the insertion order, simply switch the order in which you unpack the values when using the spread operator.

Further Reading #

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.