Sub topic 5
Removing Elements with difference
This chapter assumes you can create and iterate a Set, and that you know union and intersection return a new Set without changing their inputs. Here we cover difference, the one basic set operation where the order of the two sets changes the answer.
What difference Returns
a.difference(b) returns a new Set holding every element of a that is not in b. Elements that exist only in b never appear in the result. Neither a nor b is modified.
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log([...a.difference(b)]); // [1, 2]
console.log([...b.difference(a)]); // [5]
console.log(a.size, b.size); // 4 3 (both unchanged)In math notation this is A \ B, sometimes read as "A minus B". It is the only basic composition method that is not commutative. union and intersection give the same elements whichever set you call them on, but difference does not.
Reading the Call Correctly
It helps to read the call as a sentence. The receiver is the set you start from. The argument holds the elements you want removed.
| Expression | Read as | Result for the sets above |
|---|---|---|
| `a.difference(b)` | a, without anything in b | `{1, 2}` |
| `b.difference(a)` | b, without anything in a | `{5}` |
| `a.difference(a)` | a, without itself | empty Set |
| `a.difference(new Set())` | a, without nothing | copy of `{1, 2, 3, 4}` |
The last row is a handy idiom. Subtracting an empty set gives you a shallow copy of a, though new Set(a) says the same thing more clearly.
A Worked Example: Detecting Changes
A common job is comparing an old list of IDs with a new one to find what was added and what was removed. That takes two difference calls, one in each direction.
const before = new Set(["u1", "u2", "u3", "u4"]);
const after = new Set(["u2", "u4", "u5"]);
const removed = before.difference(after);
const added = after.difference(before);
console.log("removed:", [...removed]); // removed: [ 'u1', 'u3' ]
console.log("added:", [...added]); // added: [ 'u5' ]Each result keeps the order of its receiver. removed lists u1 before u3 because that is their insertion order in before. A later chapter covers result ordering in detail.
Common Errors
Swapping the Receiver and the Argument
The most frequent bug is writing after.difference(before) when you meant the removed items. The code runs without any error and returns a plausible-looking Set, so the mistake can go unnoticed. Name the result after the question it answers, such as removed or added, so a swap stands out in review.
Expecting the Receiver to Shrink
difference does not delete anything from a. If you want to remove elements in place, loop and call delete:
const cart = new Set(["apple", "bread", "milk"]);
const outOfStock = new Set(["bread"]);
for (const item of outOfStock) {
cart.delete(item);
}
console.log([...cart]); // [ 'apple', 'milk' ]Use the in-place version only when other code shares the same Set and needs to see the change. Otherwise, write cart = cart.difference(outOfStock) (with let), which is easier to reason about.
Comparing Objects by Content
Like the other methods, difference compares elements with SameValueZero. A separate { id: 1 } object in b will not remove a different { id: 1 } object from a. Subtract sets of primitive keys such as IDs instead. Object identity gets its own chapter later.
Summary
a.difference(b)gives the elements ofathat are not inb.- Swapping the receiver and argument changes the result.
- Both inputs stay unchanged. Use
deletein a loop if you need mutation. - The result follows the receiver's insertion order.
Exercise
Given const required = new Set(["read", "write", "share"]) and const granted = new Set(["read", "delete"]), write the expression that lists the permissions a user still lacks, and give its result as an array.
Show answer
required.difference(granted). Spreading it gives ["write", "share"]. "delete" does not appear because difference only returns elements of the receiver, and "read" is removed because granted contains it.
Exercise
After running const x = new Set([1, 2]); const y = x.difference(new Set([2])); what are [...x] and [...y]?
Show answer
[...x] is [1, 2] because difference does not modify the receiver. [...y] is [1].