JavaScript Snippet

Set Intersection and Difference

Difficulty: Medium

Computing the items shared between two arrays, the items in the first but not the second, or the symmetric difference is a routine task: comparing API responses, diffing user selections, finding new vs. removed records. This snippet shows the classic `Set`-backed implementations, an object-aware `byKey` variant, and the new native `Set.prototype.intersection` / `difference` methods that landed in Node 22 and 2024 browsers.

Code Snippets
/

Set Intersection and Difference

Set Intersection and Difference

Computing the items shared between two arrays, the items in the first but not the second, or the symmetric difference is a routine task: comparing API responses, diffing user selections, finding new vs. removed records. This snippet shows the classic `Set`-backed implementations, an object-aware `byKey` variant, and the new native `Set.prototype.intersection` / `difference` methods that landed in Node 22 and 2024 browsers.

JavaScript
Medium
4 snippets
arrays
set
utility
sets-logic

757 views

6

All three operations boil down to a hash lookup against the other side. Building one Set from b makes every membership test O(1), so the overall pass is O(|a| + |b|) instead of the O(|a| * |b|) you would get from array.includes in a filter. Wrapping a in a fresh Set first dedupes the result, which matches the mathematical definition of these operations. Note that difference is asymmetric: difference(a, b) is "in a, not in b", and symmetricDifference is the union of both halves.