Ad space (banner)
🟨JavaScript Lessons
Lesson 62 / 69

Set Operations with Set (Union, Intersection, and Difference)

In this lesson you'll learn set operations by combining Set with filter and the spread operator, so you can perform data processing that compares multiple groups. This is for people searching "JavaScript set operations union."

Combining Set with the spread syntax and filter() lets you compute a "union," "intersection," and "difference." JavaScript doesn't have dedicated set-operation methods, but this combination is the standard approach. A union is every element contained in either set; an intersection is the elements common to both; a difference is the elements found in only one.

The sample code computes the union with new Set([...a, ...b]), the intersection with [...a].filter((x) => b.has(x)), and the difference with [...a].filter((x) => !b.has(x)). The heart of this implementation is expanding a Set into an array and then using .filter() to judge "is this also contained in the other Set."

A common beginner stumbling block is understanding what each set operation actually means. It helps to draw a Venn diagram and picture which region each of the union, intersection, and difference represents, comparing that against the code. This idea is also similar to SQL's JOIN operation, so this knowledge will come in handy when you study databases too.

This is a useful way of thinking for real data-processing tasks too, like finding "users common to both groups" or "products that exist in only one." It's an idea with a lot of real-world applications, such as data analysis and grouping users.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)