How to merge sets - JavaScript

Mo Ibra

Mo Ibra

Jan 5, 2023

In this article we will learn how to merge sets in JavaScript.

It is very common to merge sets in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to merge sets.

Now let's imagine that we have an Set with a set of numbers like this:

const set1 = new Set([1, 2, 3]);
const set2 = new Set([4, 5, 6]);

And we want to merge two of them, to became output like this:

Set(6) { 1, 2, 3, 4, 5, 6 }

How to solve this problem?

To solve this problem, we can use more than one method, such as:

  • Using spread operator ....
  • Using concat method.

Merge two sets using spread operator ...

We can use spread operator to merge two sets in JavaScript.

Let's see an example

// Sets
const set1 = new Set([1, 2, 3]);
const set2 = new Set([4, 5, 6]);

// Merge two sets
const set3 = new Set([...set1, ...set2]);

Output

Set(6) { 1, 2, 3, 4, 5, 6 }

Merge two sets using concat method

We can use concat method to solve this problem as well.

But we should convert sets to arrays first and then use concat method.

Example

// Sets
const set1 = new Set([1, 2, 3]);
const set2 = new Set([4, 5, 6]);

// Convert to array
const toArr1 = Array.from(set1);
const toArr2 = Array.from(set2);

// Concat two arrays
const merge = toArr1.concat(toArr2);

// Convert to set
const set3 = new Set(merge);

// Result:
console.log(set3);

Output

Set(6) { 1, 2, 3, 4, 5, 6 }

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: