Explain Codes LogoExplain Codes Logo

Simplest way to merge ES6 Maps/Sets?

javascript
promises
callbacks
performance
Anton ShumikhinbyAnton Shumikhin·Jan 23, 2025
TLDR
// Merge Maps: Union of key-value pairs const map1 = new Map([['a', 1], ['b', 2]]); const map2 = new Map([['c', 3], ['b', 4]]); const mergedMap = new Map([...map1, ...map2]); // { 'a' => 1, 'b' => 4, 'c' => 3 } // Merge Sets: Union of distinct values const set1 = new Set([1, 2]); const set2 = new Set([2, 3]); const mergedSet = new Set([...set1, ...set2]); // { 1, 2, 3 }

Combine Maps keeping latest values in key conflicts; merge Sets keeping unique elements only.

Behavior of key conflicts during merge

Pay attention when merging Maps using spread syntax: duplicate keys will take on the value from the last Map. As Spider-Man's uncle said, "With great power, comes great responsibility," so plan for such scenarios:

const map1 = new Map([['a', 1]]); const map2 = new Map([['a', 2]]); // Here value `2` in `map2` overwrites `1` in `map1` for the key 'a' const merged = new Map([...map1, ...map2]); // Winner is the last one standing, Result: { 'a' => 2 }

Let's level up: Advanced merging

Generators for diplomatic merging

Who needs conversions from sets or maps to arrays when we've got generators for neat merging?

function* mergeSets(sets) { for (let set of sets) { yield* set; } } // Here combinedSet calls this generator and obediently collects the yield results. const combinedSet = new Set(mergeSets([set1, set2]));

Subclass for smart operations

You could level up the Set class into a subclass (SetEx), bring in handy methods like .merge(). It's like teaching an old dog new tricks.

class SetEx extends Set { merge(...sets) { for (let set of sets) { for (let elem of set) { // Yes, we can learn new things. this.add(elem); } } } }

It doesn’t have to be snail pace: Benchmark performance

Always check the performance of your fancy strategies. No one likes to keep their code waiting. Here's a teaser of how to benchmark Set merging:

// Ready, Steady, Go! console.time("Spread Operator"); // Merge in progress... drum-rolls please var merged = new Set([...set1, ...set2]); // Let's see how long that took. console.timeEnd("Spread Operator"); // Ah, not bad at all!

When mutation is a big NO

To prevent altering the original Maps/Sets during the merge, ensure to work with their copies. After all, we respect personal boundaries.

// For Sets, catering to uniqueness. const set1Copy = new Set(set1); const set2Copy = new Set(set2); // Viola! Merged without any scars. const mergedSet = new Set([...set1Copy, ...set2Copy]); // Doing the same for Maps const map1Copy = new Map(map1); const map2Copy = new Map(map2); // Merged like the butter in hot pan. const mergedMap = new Map([...map1Copy, ...map2Copy]);

Future is calling

Don’t forget to keep an eye out for the next big thing in JavaScript - .union(). Welcome to the future of merging.

// Shiny future syntax of tomorrow, hopefully. const mergedSet = set1.union(set2);

Check GitHub proposals and compatibility tables to stay abreast with ECMAScript gossips.