Check if two arrays intersect
JavaScript, Array · Feb 17, 2023

Determines if two arrays have a common item.
- Create a
Set
fromb
to get the unique values inb
. - Use
Array.prototype.some()
ona
to check if any of its values are contained inb
, usingSet.prototype.has()
.
const intersects = (a, b) => {
const s = new Set(b);
return [...new Set(a)].some(x => s.has(x));
};
intersects(['a', 'b'], ['b', 'c']); // true
intersects(['a', 'b'], ['c', 'd']); // false
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.