Comparing Sets With isSubsetOf()

Rosa’s report now shows who helped. Eight of the nine plot holders came, and the report thanks Ben Carter and Gus Tanaka for coming to both work days. The committee has questions of its own. Did all three committee members turn up? Did the spring and autumn crowds overlap? And was the spring crowd the same as last year’s?

Python answers them with operators such as <= and ^, or methods such as isdisjoint(). JavaScript has only the methods, and you’ll meet the one question that no JavaScript operator or method answers for you. Start with the committee.

Ask Whether One Set Holds Another

The committee is Ana Lima, Fatima Sheikh, and Gus Tanaka, and they want to know whether all three helped. In Python, <= asks whether one set is a subset of another, and a difference names anyone missing:

Language: Python
COMMITTEE = {"Ana Lima", "Fatima Sheikh", "Gus Tanaka"}
print(COMMITTEE <= helped)
print(COMMITTEE - helped)

It prints False, then {'Fatima Sheikh'}. JavaScript spells the subset test .isSubsetOf(), the camelCase twin of Python’s issubset(), and .difference() works as it did for the reminder line. Here’s the check, with helped built from the union of spring and autumn:

Language: JavaScript
const spring = new Set([
  "Ana Lima", "Ben Carter", "Chloe Park",
  "Dara Quinn", "Gus Tanaka", "Hana Uddin",
]);
const autumn = new Set([
  "Ben Carter", "Eli Ross", "Gus Tanaka", "Ivan Volkov",
]);
const helped = spring.union(autumn);

const COMMITTEE = new Set(["Ana Lima", "Fatima Sheikh", "Gus Tanaka"]);
console.log(COMMITTEE.isSubsetOf(helped));
console.log(COMMITTEE.difference(helped));

Fatima Sheikh came to neither work day, so the committee isn’t a subset of helped:

Language: Program Output
false
Set(1) { 'Fatima Sheikh' }

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.