Menu

1 / 4

JavaScript Set Algebra Explained: Master Union, Intersection, Difference, and Symmetric Difference

JavaScript in Plain English - Medium·Zayd Islam·7 days ago
#7HZ524sV
Reading 0:00
15s threshold

Member-only story

JavaScript Set Algebra Explained: Master Union, Intersection, Difference, and Symmetric Difference

JavaScript Mastery Series Part 46

Zayd Islam

7 min read11 hours ago

Read Part 45

Press enter or click to view image in full size

Imagine you have two groups of users.

One group subscribed to your newsletter. Another group purchased a product.

You want to answer questions like:

  • Who belongs to both groups?
  • Who belongs to either group?
  • Who subscribed but never purchased?
  • Who belongs to exactly one group?

You could write several loops, nested conditions, and filtering functions.

Or you could use something much more elegant: Set algebra.

JavaScript’s Set has evolved beyond simply storing unique values. Modern JavaScript provides built-in methods for performing mathematical set operations.

Let’s explore them with practical examples.

1. First, what is a Set?

A JavaScript Set is a collection of unique values.

const numbers = new Set([1, 2, 2, 3, 3, 4]);
console.log(numbers);
// Set(4) { 1, 2, 3, 4 }