How to merge Sets using JavaScript


Borislav Hadzhiev

Last updated: Oct 28, 2021


Check out my new book

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 #

Use the search field on my Home Page to filter through my more than 3,000 articles.