Sub topic 12
Putting Set Methods to Work
This chapter brings the earlier material together into patterns you can use in real code. It assumes you already know how union, intersection, difference, symmetricDifference, and the three predicates behave, and that you are comfortable with Array.prototype.filter, map, and reduce. Each pattern below solves one common task: checking permissions, syncing ID lists, filtering by tags, toggling selections, and combining many sets at once. Each pattern also points out where the set methods help and where they can trip you up.
Choosing the Right Method for the Task
Most set-related tasks reduce to a question about two collections. If you name the question, you usually know which method to call.
| Question you are asking | Method | Returns |
|---|---|---|
| What do both collections have together? | `a.union(b)` | New Set |
| What do they share? | `a.intersection(b)` | New Set |
| What does `a` have that `b` lacks? | `a.difference(b)` | New Set |
| What changed between them? | `a.symmetricDifference(b)` | New Set |
| Does `b` contain everything in `a`? | `a.isSubsetOf(b)` | Boolean |
| Do they share nothing? | `a.isDisjointFrom(b)` | Boolean |
| Do they share anything? | `!a.isDisjointFrom(b)` | Boolean |
Use a predicate when you only need a yes or no answer. It skips building a result Set and can stop early.
Pattern 1: Permission Checks
Access control is the classic subset problem. An action requires some permissions, and a user holds some permissions. The user may act only if the required set is a subset of the granted set.
const required = new Set(["read", "write", "publish"]);
const granted = new Set(["read", "write"]);
console.log(required.isSubsetOf(granted)); // false
const missing = required.difference(granted);
console.log([...missing]); // ["publish"]The check and the error message use different methods. isSubsetOf answers "may they?", and difference answers "what are they missing?". Error messages and audit logs need that second answer.
Users often get permissions through several roles. In that case, compute their effective permissions with union:
const rolePermissions = new Map([
["viewer", new Set(["read"])],
["editor", new Set(["read", "write"])],
["publisher", new Set(["publish"])],
]);
function permissionsFor(roles) {
return roles.reduce(
(acc, role) => acc.union(rolePermissions.get(role) ?? new Set()),
new Set()
);
}
const effective = permissionsFor(["editor", "publisher"]);
console.log([...effective]); // ["read", "write", "publish"]
const action = new Set(["read", "publish"]);
console.log(action.isSubsetOf(effective)); // trueThe ?? new Set() fallback matters. If a role name is unknown, rolePermissions.get(role) returns undefined. Passing undefined to union throws a TypeError, because undefined is not set-like.
Blocking Forbidden Combinations
Some systems also have a deny list. Here isDisjointFrom states the rule directly: the user's permissions must not overlap the forbidden ones.
const forbiddenForContractors = new Set(["delete", "admin"]);
const contractor = new Set(["read", "write", "delete"]);
if (!contractor.isDisjointFrom(forbiddenForContractors)) {
const violations = contractor.intersection(forbiddenForContractors);
console.log(`Not allowed: ${[...violations].join(", ")}`); // Not allowed: delete
}Pattern 2: Syncing Two ID Lists
You often have a previous snapshot of IDs and a current one, for example the members of a mailing list before and after an import. You need to know which IDs were added, which were removed, and which stayed. Two difference calls and one intersection give you all three.
function diffIds(previous, current) {
const before = new Set(previous);
const after = new Set(current);
return {
added: after.difference(before),
removed: before.difference(after),
kept: before.intersection(after),
};
}
const { added, removed, kept } = diffIds([101, 102, 103], [102, 103, 104, 105]);
console.log([...added]); // [104, 105]
console.log([...removed]); // [101]
console.log([...kept]); // [102, 103]The inputs are arrays, so the function wraps them with new Set(...) before calling any method. Forgetting that wrap is the most common bug in this pattern. after.difference(previousArray) throws a TypeError because arrays have no size property.
If you only need to know whether anything changed at all, symmetricDifference gives you the added and removed IDs in one call:
const before = new Set([101, 102, 103]);
const after = new Set([102, 103, 104]);
const changed = before.symmetricDifference(after);
console.log(changed.size > 0); // true
console.log([...changed]); // [101, 104]Pattern 3: Filtering by Tags
Tag filters come in three flavors, and each maps to one predicate:
- Match all: the post must have every selected tag, so the selected tags must be a subset of the post's tags.
- Match any: the post must have at least one selected tag, so the two sets must not be disjoint.
- Exclude: the post must have none of the excluded tags, so the two sets must be disjoint.
const posts = [
{ title: "Intro to Sets", tags: new Set(["js", "data-structures"]) },
{ title: "CSS Grid", tags: new Set(["css", "layout"]) },
{ title: "Set Methods", tags: new Set(["js", "es2025", "data-structures"]) },
];
const mustHaveAll = new Set(["js", "data-structures"]);
const mustHaveAny = new Set(["css", "es2025"]);
const excluded = new Set(["layout"]);
const titles = (list) => list.map((p) => p.title);
console.log(titles(posts.filter((p) => mustHaveAll.isSubsetOf(p.tags))));
// ["Intro to Sets", "Set Methods"]
console.log(titles(posts.filter((p) => !p.tags.isDisjointFrom(mustHaveAny))));
// ["CSS Grid", "Set Methods"]
console.log(titles(posts.filter((p) => p.tags.isDisjointFrom(excluded))));
// ["Intro to Sets", "Set Methods"]Watch the receiver in the match-all filter. mustHaveAll.isSubsetOf(p.tags) asks "is every selected tag on the post?", which is correct. p.tags.isSubsetOf(mustHaveAll) asks the reverse question, "is every tag on the post selected?". It would wrongly reject "Set Methods" because of its extra es2025 tag.
Pattern 4: Toggling a Selection
In a multi-select UI, clicking a group of items should select the ones that were off and deselect the ones that were on. That is exactly what symmetricDifference does.
let selected = new Set(["a", "b"]);
selected = selected.symmetricDifference(new Set(["b", "c"]));
console.log([...selected]); // ["a", "c"]Because the method returns a new Set, reassigning selected gives you a new reference each time. UI frameworks that detect changes by comparing references, such as React state updates, notice the change without extra work. If you had mutated the Set with add and delete, they would not.
Pattern 5: Testing Two Sets for Equality
JavaScript has no Set.prototype.equals, and === compares references. Two sets are equal when they have the same size and one is a subset of the other:
function setsEqual(a, b) {
return a.size === b.size && a.isSubsetOf(b);
}
console.log(setsEqual(new Set([1, 2, 3]), new Set([3, 2, 1]))); // true
console.log(setsEqual(new Set([1, 2]), new Set([1, 2, 3]))); // falseOrder does not matter here, which is what you want for sets. The size check runs first and is cheap. When the sizes match, isSubsetOf stops at the first missing element. An alternative is a.symmetricDifference(b).size === 0. It gives the same answer but always builds a full result Set.
Pattern 6: Combining Many Sets
The methods take exactly one argument. To combine a list of sets, fold over it with reduce:
function intersectAll(sets) {
if (sets.length === 0) return new Set();
const bySize = [...sets].sort((x, y) => x.size - y.size);
return bySize.reduce((acc, s) => acc.intersection(s));
}
function unionAll(sets) {
return sets.reduce((acc, s) => acc.union(s), new Set());
}
const monday = new Set(["ana", "ben", "cy", "dee"]);
const tuesday = new Set(["ben", "cy"]);
const wednesday = new Set(["cy", "ben", "eve"]);
console.log(intersectAll([monday, tuesday, wednesday]).size); // 2 (ben and cy)
console.log(unionAll([monday, tuesday, wednesday]).size); // 5Sorting by size before intersecting is a cheap optimization. The running result can never grow larger than the smallest set, so starting from the smallest set keeps every later step small.
intersectAll returns an empty Set for an empty list. Mathematically, the intersection of no sets is "everything", and JavaScript cannot represent that. Make this choice explicit in your own code, because callers may expect a different behavior.
Pattern 7: Working with Objects and Maps
Records from an API are usually objects, and two objects with the same contents are different Set elements. Convert records to their IDs, run the set operation on the IDs, and then map back to the records:
const teamA = [{ id: 1, name: "Ada" }, { id: 2, name: "Linus" }];
const teamB = [{ id: 2, name: "Linus" }, { id: 3, name: "Grace" }];
const idsA = new Set(teamA.map((u) => u.id));
const idsB = new Set(teamB.map((u) => u.id));
const sharedIds = idsA.intersection(idsB);
const sharedUsers = teamA.filter((u) => sharedIds.has(u.id));
console.log(sharedUsers.map((u) => u.name)); // ["Linus"]If you already keep records in a Map keyed by ID, you can skip the conversion. A Map is set-like through its keys, so you can pass it directly:
const usersById = new Map([
[1, { name: "Ada" }],
[2, { name: "Linus" }],
[3, { name: "Grace" }],
]);
const onlineIds = new Set([2, 3, 9]);
const knownOnline = onlineIds.intersection(usersById);
console.log([...knownOnline].map((id) => usersById.get(id).name)); // ["Linus", "Grace"]
const unknownOnline = onlineIds.difference(usersById);
console.log([...unknownOnline]); // [9]Common Mistakes in Practice
- Passing an array instead of a Set. Wrap it first with
new Set(array). - Passing
undefinedfrom a failed lookup. Supply a default such as?? new Set(). - Reversing the receiver in
differenceorisSubsetOf. Reada.difference(b)as "a without b" anda.isSubsetOf(b)as "a fits inside b". - Expecting objects with equal contents to match. Compare IDs or other primitive keys instead.
- Relying on result order for display. If the order matters, sort the result explicitly with
[...result].sort(). - Shipping to older runtimes without checking support. Use the feature-detected helpers from the previous chapter.
Exercise
A deployment requires the permissions "deploy" and "read-logs". Write a function canDeploy(userRoles) that uses the rolePermissions Map from Pattern 1 (extended with ["ops", new Set(["deploy", "read-logs"])]). It should return { ok: true } when the user has both permissions, and { ok: false, missing: [...] } otherwise.
Show answer
const needed = new Set(["deploy", "read-logs"]); function canDeploy(userRoles) { const effective = userRoles.reduce((acc, r) => acc.union(rolePermissions.get(r) ?? new Set()), new Set()); return needed.isSubsetOf(effective) ? { ok: true } : { ok: false, missing: [...needed.difference(effective)] }; } With ["ops"] it returns { ok: true }. With ["editor"] it returns { ok: false, missing: ["deploy", "read-logs"] }.
Exercise
A colleague writes posts.filter((p) => p.tags.isSubsetOf(selected)) to show posts that have all selected tags. What does this actually do, and how do you fix it?
Show answer
It keeps posts whose tags are all among the selected tags, so any post with an extra tag is dropped, and posts with no tags at all are always kept. The fix is to reverse the receiver: selected.isSubsetOf(p.tags), which asks whether every selected tag appears on the post.
Exercise
Given const prev = [5, 6, 7] and const next = [7, 8], what do diffIds(prev, next).added, .removed, and .kept contain, and what does new Set(prev).symmetricDifference(new Set(next)) contain?
Show answer
added is {8}, removed is {5, 6}, and kept is {7}. The symmetric difference is {5, 6, 8}: the removed IDs followed by the added ones.