liveBook · Manning

Set intersection

As explained in Secrets of the JavaScript Ninja, Second Edition

A set operation that produces a set containing the elements common to the operand sets.

When two collections overlap, their intersection keeps only members present in both. With JavaScript Sets, this finds shared items such as people who belong to two groups. section 9.3.3

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

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

assert(ninjaSamurais.size === 1, "There's only one ninja samurai");
assert(ninjaSamurais.has("Hattori"), "Hattori is his name");

Spread one Set into an array, filter for values present in the other Set, then wrap the matches in a new Set. Here, Hattori is the only shared member. section 9.3.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines the common-elements result and demonstrates an implementation using spread, filter(), and has().
Examples
Demonstrates intersecting ninja and samurai Sets, yielding Hattori as the sole shared member.
What it assumes
Assumes familiarity with JavaScript Sets, arrays, filter(), and spread syntax; does not build those features from scratch.
What you can do after
Build an intersection by filtering one Set’s values with the other Set’s has() method and wrapping the matches in a new Set.
How it connects
Connects Set intersection to array conversion with spread syntax and filtering with Array.filter().

Also explained in

Compare how 5 books explain set intersection →

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.