How to merge Sets using JavaScript


Borislav Hadzhiev

Thu Oct 28 20211 min read

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 example looks like:

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 #

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