We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Set Composition

I'll be 10000% honest, I don't often use these fancy set composition methods... but maybe I should. They're pretty neat. In most of my work I just use sets to check for existence or de-duplicate values. But, if you're versed in set theory, you might find these methods useful.

Intersection

The .intersection() method returns a new set containing the elements that are in both sets.

const heroes = new Set(["eren", "mikasa", "armin", "reiner"]);
const villains = new Set(["eren", "reiner", "bertholdt", "annie"]);
const samesies = heroes.intersection(villains);
console.log(samesies);
// Set { 'eren', 'reiner' }

Difference

The .difference() method returns a new set containing the elements that are in the first set but not in the second set.

const heroes = new Set(["eren", "mikasa", "armin", "reiner"]);
const villains = new Set(["eren", "reiner", "bertholdt", "annie"]);
const nonVillains = heroes.difference(villains);
console.log(nonVillains);
// Set { 'mikasa', 'armin' }

Union

The .union() method returns a new set containing the elements that are in either set.

const heroes = new Set(["eren", "mikasa", "armin", "reiner"]);
const villains = new Set(["eren", "reiner", "bertholdt", "annie"]);
const everyone = heroes.union(villains);
console.log(everyone);
// Set { 'eren', 'mikasa', 'armin', 'reiner', 'bertholdt', 'annie' }

There are some more set methods, but those are the big three.