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