Union, intersection and difference of arrays in JavaScript
Intermediate · 3 min read
Comparing two lists is an everyday job. Which users are in both groups? Which products are in stock but not on sale? Which tags were added since the last save? Those questions have names from school maths: union, intersection and difference.
In this tutorial you will write all of them for [1, 2, 3, 4] and [3, 4, 5], using a Set so each check is fast. You will also see why the order of the arguments matters for difference. You should know arrays, filter, spread (...) and arrow functions.
The five answers in words
With a = [1, 2, 3, 4] and b = [3, 4, 5]:
- Union: everything in either list, once each.
[1, 2, 3, 4, 5]. - Intersection: what both lists have.
[3, 4]. - a minus b: what
ahas thatbdoesn't.[1, 2]. - b minus a: what
bhas thatadoesn't.[5]. - Symmetric difference: what only one of them has.
[1, 2, 5].
Why a Set
A Set is a built-in collection that holds each value once. Its has method checks whether a value is in it, and that check is fast however big the Set is. An array's includes has to look through the items one by one.
const inB = new Set([3, 4, 5]);
console.log(inB.has(4)); // true
console.log(inB.has(1)); // false
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
38 Union, intersection and difference
fairGiven [1, 2, 3, 4] and [3, 4, 5], produce the union, the intersection, both differences, and the symmetric difference.
Stuck? Three hints, smallest first
- 1. Put the second list in a
Setfirst, so each membership test is one lookup rather than a scan. - 2. De-duplicate the first list too, or a repeated value appears twice in the answer.
- 3. Difference is not symmetric:
a \ bandb \ aare different questions.
Step 1: union
Join both lists with spread, then let a Set drop the repeats.
const union = (a, b) => [...new Set([...a, ...b])];
console.log(union([1, 2, 3, 4], [3, 4, 5])); // [ 1, 2, 3, 4, 5 ]
[...a, ...b] is [1, 2, 3, 4, 3, 4, 5]. The Set keeps the first 3 and 4 and ignores the second ones.
Step 2: intersection
Keep the items of a that b also has. Build a Set from b once, then check each item of a against it.
const intersection = (a, b) => {
const inB = new Set(b);
return a.filter((v) => inB.has(v));
};
console.log(intersection([1, 2, 3, 4], [3, 4, 5])); // [ 3, 4 ]
console.log(intersection([3, 3, 4], [3, 4])); // [ 3, 3, 4 ]
The first line is right. The second is the wrong turn: a had 3 twice, so the answer has 3 twice. An intersection should list each value once.
Step 3: de-duplicate a as well
Run a through a Set first, then filter.
const intersection = (a, b) => {
const inB = new Set(b);
return [...new Set(a)].filter((v) => inB.has(v));
};
console.log(intersection([3, 3, 4], [3, 4])); // [ 3, 4 ]
console.log(intersection([1, 2, 3, 4], [])); // []
Now repeats don't multiply. Intersecting with an empty list gives nothing, because nothing is in both.
Why not just write b.includes(v) and skip the Set? It gives the same answer, but includes searches all of b for every item of a. For two lists of 10,000 items, that is up to 100 million checks. With one Set built up front, it is 10,000 quick lookups.
Step 4: difference, both ways
Difference is intersection with the test flipped: keep what b does not have.
const difference = (a, b) => {
const inB = new Set(b);
return [...new Set(a)].filter((v) => !inB.has(v));
};
const a = [1, 2, 3, 4];
const b = [3, 4, 5];
console.log(difference(a, b)); // [ 1, 2 ]
console.log(difference(b, a)); // [ 5 ]
Swap the arguments and you get a different answer. "Difference" on its own is a vague name: it matters which list you start from. In your own code, a name like missingFrom(a, b) or a short comment saves someone a bug.
Step 5: symmetric difference
Everything that is in only one of the lists is both differences joined together.
const difference = (a, b) => {
const inB = new Set(b);
return [...new Set(a)].filter((v) => !inB.has(v));
};
const symmetric = (a, b) => [...difference(a, b), ...difference(b, a)];
console.log(symmetric([1, 2, 3, 4], [3, 4, 5])); // [ 1, 2, 5 ]
Step 6: the built-in Set methods
Newer engines give Sets their own union, intersection, difference and symmetricDifference methods. They are recent, so test for them first.
const hasSetMethods = typeof new Set().union === 'function';
console.log(hasSetMethods); // true
if (hasSetMethods) console.log([...new Set([1, 2, 3, 4]).union(new Set([3, 4, 5]))]); // [ 1, 2, 3, 4, 5 ]
hasSetMethods is true in node 26; an older browser may say false. These methods take a Set and return a Set, so you spread the result to get an array.
The full solution
The panel defines all five functions and prints each answer for the two lists, plus the built-in union where your browser has it. Press Run and compare "a minus b" with "b minus a".
const union = (a, b) => [...new Set([...a, ...b])];
const intersection = (a, b) => {
const inB = new Set(b); // one Set, then n lookups
return [...new Set(a)].filter((v) => inB.has(v));
};
const difference = (a, b) => {
const inB = new Set(b);
return [...new Set(a)].filter((v) => !inB.has(v));
};
const symmetric = (a, b) => [...difference(a, b), ...difference(b, a)];
const a = [1, 2, 3, 4];
const b = [3, 4, 5];
const hasSetMethods = typeof new Set().union === 'function';
const builtInUnion = hasSetMethods ? [...new Set(a).union(new Set(b))] : union(a, b);
console.log('union :', union(a, b));
console.log('intersection :', intersection(a, b));
console.log('a minus b :', difference(a, b));
console.log('b minus a :', difference(b, a), '<- not the same question');
console.log('symmetric :', symmetric(a, b));
console.log('duplicates do not multiply:', intersection([3, 3, 4], [3, 4]));
console.log('Set methods available?', hasSetMethods, '->', builtInUnion);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the union holds each value once', union(a, b), [1, 2, 3, 4, 5]);
test('the intersection is what both have', intersection(a, b), [3, 4]);
test('a minus b', difference(a, b), [1, 2]);
test('b minus a is a different answer', difference(b, a), [5]);
test('so difference is not symmetric', same(difference(a, b), difference(b, a)), false);
test('the symmetric difference is both leftovers', symmetric(a, b), [1, 2, 5]);
test('a repeated value appears once in the result', intersection([3, 3, 4], [3, 4]), [3, 4]);
test('intersecting with an empty list gives nothing', intersection(a, []), []);
test('the built-in Set methods agree where the engine has them', builtInUnion, [1, 2, 3, 4, 5]);
The Set is not a style choice, it is the algorithm. Written with b.includes(v) instead, intersection re-scans b for every element of a — fine for ten items, and quadratic for ten thousand. Building one Set up front makes each test a hash lookup.
De-duplicating a matters too: without the inner new Set(a), intersection([3, 3, 4], [3, 4]) would return [3, 3, 4], which is no longer a set. And the two differences being different answers is worth stating out loud, because "difference" in a function name without an argument order convention is a bug waiting to happen.
Common mistakes
- Using
includesinsidefilteron big lists. It searches the whole second list for every item. Build a Set once. - Forgetting to de-duplicate the first list. Repeated values show up repeatedly in the answer.
- Swapping the arguments to
difference.difference(a, b)anddifference(b, a)answer different questions.
Try it yourself
- Given last week's and this week's tag lists, find the tags that were added and the ones that were removed.
- Write
isSubset(a, b)that istruewhen every item ofais inb. - Find the students who signed up for both
['Ada', 'Bola', 'Chi']and['Chi', 'Dami', 'Ada'].