brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Set.union() merges two sets without the spread trick

Javascript
~/tips/tip-javascript-set-union

// Set { "docker", "tmux", "git", "python" }

Combines two JavaScript sets into a new one with a built-in method.

For years, merging two sets in JavaScript meant new Set([...a, ...b]). It works, but it reads like a workaround. Sets now have real methods for this.

const mine = new Set(["docker", "tmux", "git"]);
const yours = new Set(["git", "python"]);

mine.union(yours);
// Set { "docker", "tmux", "git", "python" }

union() returns a new set with everything in either set. Neither original changes. MDN says the elements of the first set come first, followed by the new ones from the other set. MDN also lists sibling methods, among them intersection() for what both have and difference() for what’s in the first and not in the second.

An example where this reads much better: tags a user picked plus tags from their saved filters, without duplicates.

const active = selectedTags.union(savedFilterTags);

The argument has to be a Set or a set-like object. If you have an array, wrap it first: mine.union(new Set(list)).

Caveat: MDN marks it Baseline 2024, available since June 2024. Current browsers and recent Node versions are fine, but if you support older devices, keep the spread version or add a polyfill.

Further reading: MDN: Set.prototype.union()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link