Skip to main content

How to Merge Set Objects in JavaScript

A common task when working with Set objects is to combine two or more of them into a single Set that contains all the unique elements from the source sets. This is the equivalent of a "union" operation in set theory.

This guide will demonstrate the most modern and idiomatic method for merging Set objects using the spread syntax (...). We will also cover a more traditional approach using a for...of loop for a complete understanding of the process.

The cleanest, most concise, and most common way to merge Set objects is to spread their elements into a new Set constructor.

For example, you have multiple Set objects and want to combine them into one.

// Problem: Combine these two sets into a single new set.
const set1 = new Set(['apple', 'banana']);
const set2 = new Set(['banana', 'cherry']);

Solution: the spread syntax (...) elegantly unpacks the elements of each Set into the constructor of the new Set.

const set1 = new Set(['apple', 'banana']);
const set2 = new Set(['banana', 'cherry']);

// Use the spread syntax to combine them.
const mergedSet = new Set([...set1, ...set2]);

console.log(mergedSet);
// Output: Set(3) { 'apple', 'banana', 'cherry' }
note

This single line of code is all you need. The Set constructor automatically handles the deduplication (notice "banana" appears only once).

An Alternative Method: Using a for...of Loop

A more traditional, imperative approach is to create a new Set and then iterate over the source sets, adding each element individually. This is more verbose but is useful for understanding the underlying process.

Solution:

function mergeSets(...sets) {
const newSet = new Set();

for (const aSet of sets) {
for (const element of aSet) {
newSet.add(element);
}
}

return newSet;
}

// Example Usage:
const set1 = new Set(['apple', 'banana']);
const set2 = new Set(['banana', 'cherry']);
const mergedSet = mergeSets(set1, set2);

console.log(mergedSet);
// Output: Set(3) { 'apple', 'banana', 'cherry' }
note

This function works by looping through each Set provided and then looping through each element within that Set, adding it to the master Set. The Set.add() method inherently ignores duplicates.

How the Spread Syntax Method Works

The one-liner new Set([...set1, ...set2]) is a powerful combination of modern JavaScript features. Let's break it down.

Step 1: Unpack the Set Objects into an Array

The spread syntax (...) when used on an iterable object like a Set, unpacks its elements into a list. We use it to create a new, temporary array containing all elements from all the source sets.

const set1 = new Set(['apple', 'banana']);
const set2 = new Set(['banana', 'cherry']);

const combinedArray = [...set1, ...set2];

console.log(combinedArray);
// Output: ['apple', 'banana', 'banana', 'cherry']

Step 2: Create a New Set from the Array

The Set() constructor can accept any iterable object (including an array) as its argument. When it does, it iterates over the elements and adds each one, automatically discarding any duplicates.

const combinedArray = ['apple', 'banana', 'banana', 'cherry'];
const finalSet = new Set(combinedArray);

console.log(finalSet);
// Output: Set(3) { 'apple', 'banana', 'cherry' }

This two-step process is what happens behind the scenes in the concise one-liner.

A Note on Insertion Order

Set objects in JavaScript preserve the insertion order of their elements. When you merge sets, the order of the final Set is determined by the order in which you spread the source sets.

Example:

const set1 = new Set(['apple']);
const set2 = new Set(['banana']);

// Spreading set1 first
const merged1 = new Set([...set1, ...set2]);
console.log(Array.from(merged1)); // Output: ['apple', 'banana']

// Spreading set2 first
const merged2 = new Set([...set2, ...set1]);
console.log(Array.from(merged2)); // Output: ['banana', 'apple']
note

This gives you predictable control over the final order of elements in your merged Set.

Conclusion

Merging Set objects is a simple task with a clear, modern solution.

  • The spread syntax (...) is the overwhelmingly recommended best practice. It is concise, declarative, readable, and efficient: new Set([...set1, ...set2]).
  • The for...of loop is a valid but more verbose, imperative alternative. It is useful for understanding the process but is not the preferred method for modern code.

By leveraging the power of the spread syntax and the Set constructor, you can perform set union operations in a single, elegant line of code.