Array Intersection, Union & Difference
Array Intersection, Union & Difference is a reusable JavaScript snippet. Set-like operations for arrays: find common elements (intersection), combine unique elements (union), and find differences. The full implementation: const arrayOps = { // Elements present in both arrays intersection: (a, b) => { const setB = new Set(b) return a.filter(x => setB.has(x)) }, // All unique elements from both arrays union: (a, b) => [...new Set([...a, ...b])], // Elements in 'a' but not in 'b' difference: (a, b) => { const setB = new Set(b) return a.filter(x => !setB.has(x)) }, // Elements in either array but not both symmetricDifference: (a, b) => { const setA = new Set(a)… This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.