Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Set union, intersection and difference built in

Compare two subscriber lists with Set union, intersection and difference, and choose an explicit order when you display the result.

You have yesterday's subscriber IDs and today's. Before sending a welcome email, you need the IDs that appear in today's list alone. You can also check which IDs stayed and which dropped out without writing a separate filter for each case.

Compare membership

Make a Set from each array. That collapses duplicate IDs up front, which matters when the same subscriber appears in multiple rows of an export.

const yesterday = new Set(["b", "a", "c", "a"]);
const today = new Set(["a", "b", "d"]);

console.log([...yesterday.union(today)]);
console.log([...yesterday.intersection(today)]);
console.log([...today.difference(yesterday)]);
console.log([...yesterday.difference(today)]);

The four arrays are ["b", "a", "c", "d"], ["b", "a"], ["d"], and ["c"].

Use union when you need each ID seen on either day, and intersection when you need IDs seen on both days. Read difference from left to right. The Set before the dot supplies the candidates, and the argument supplies the IDs to exclude.

Each method returns a fresh Set, so you can compute arrivals and departures from the same inputs. The spread in the example converts the results to arrays for display. Keep the results as Sets when the next step is another membership check.

Use a Map as the second operand

The methods accept an argument with size, has() and keys(). A Map meets that contract, so you can compare a Set of IDs against the keys of a lookup table.

const recipients = new Set(["a", "b", "d"]);
const optedOut = new Map([["b", "unsubscribed"]]);

console.log([...recipients.difference(optedOut)]);

The result is ["a", "d"] because the Map supplies its keys as members.

An array of IDs lacks that contract. Wrap it in new Set(ids). If IDs come from different feeds, normalize their representations before either Set sees them. The number 42 and the string "42" are distinct members.

Choose the order before rendering

Union retains the left Set's insertion order and appends unseen members from the right. Difference retains the left Set's order. For intersection, the smaller operand drives the order, with ties going to the left.

The example prints ["b", "a"] for the intersection because both Sets have size three. Add one more member to yesterday and the same intersection reads ["a", "b"]. If the array backs a sorted list or a stable snapshot, sort it after the membership operation.