liveBook · Manning

Set union

As explained in Secrets of the JavaScript Ninja, Second Edition

A set operation that produces a set containing every element present in either operand set.

A set union combines the elements of two sets into a new set. Shared elements appear only once, so Hattori can serve on both rosters without counting as two warriors. section 9.3.2

Listing 9.21. Using sets to perform a union of collections
const ninjas = ["Kuma", "Hattori", "Yagyu"];                       #A
const samurai = ["Hattori", "Oda", "Tomoe"];                       #A

const warriors = new Set([...ninjas, ...samurai]);                 #B

assert(warriors.has("Kuma"), "Kuma is here");                      #C
assert(warriors.has("Hattori"), "And Hattori");                    #C
assert(warriors.has("Yagyu"), "And Yagyu");                        #C
assert(warriors.has("Oda"), "And Oda");                            #C
assert(warriors.has("Tomoe"), "Tomoe, last but not least");        #C

assert(warriors.size === 5, "There are 5 warriors in total");      #D

The example spreads two arrays into one, then passes the combined values to Set, which keeps Hattori only once. section 9.3.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines union and demonstrates it with array spreading and Set construction.
Examples
Uses ninja and samurai rosters, with Hattori appearing in both.
What it assumes
Assumes familiarity with arrays and spread syntax while defining sets as collections of distinct items.
What you can do after
Apply union via JavaScript's Set constructor and spread syntax to combine arrays while retaining distinct values.
How it connects
Connects sets with arrays, the spread operator, and JavaScript's Set constructor.

Also explained in

Compare how 4 books explain set union →

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.