Files
30-seconds-of-code/snippets/js/s/arrays-intersect.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

613 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Check if two arrays intersect snippet javascript
array
chalarangelo interior-5 2023-02-17T05:00:00-04:00

Determines if two arrays have a common item.

  • Create a Set from b to get the unique values in b.
  • Use Array.prototype.some() on a to check if any of its values are contained in b, using Set.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