liveBook · Manning

Set difference

As explained in Secrets of the JavaScript Ninja, Second Edition

The set of elements in one set that are not in another set.

Set difference keeps the elements in one set that are absent from another. It’s handy when you want the ninjas who aren’t also samurai. section 9.3.4

Listing 9.23. Difference of sets
const ninjas = new Set(["Kuma", "Hattori", "Yagyu"]);         
const samurai = new Set(["Hattori", "Oda", "Tomoe"]);       

const pureNinjas = new Set(
  [...ninjas].filter(ninja => !samurai.has(ninja))                #A
);

assert(pureNinjas.size === 2, "There's only one ninja samurai");
assert(pureNinjas.has("Kuma"), "Kuma is a true ninja");
assert(pureNinjas.has("Yagyu"), "Yagyu is a true ninja");

Spread the first set into an array, filter out elements found in the second set with has, then wrap the survivors in a new Set. section 9.3.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines the operation and demonstrates it with JavaScript, without developing a formal treatment.
Examples
Demonstrates filtering ninjas to exclude those who are also samurai.
What you can do after
Apply set difference with JavaScript Set, spread, filter, and has.
How it connects
Connects set difference to sets and compares its operation with set intersection.

Also explained in

Compare how 2 books explain set difference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.