Explain Codes LogoExplain Codes Logo

Check if an array contains any element of another array in JavaScript

javascript
nested-iteration
short-circuiting
intersection
Nikita BarsukovbyNikita BarsukovยทDec 6, 2024
โšกTLDR

Looking for a quick hit and run solution? Here's a one-liner using array1.some() and array2.includes() to check if array1 and array2 share any common elements.

const sharedElementExists = [1, 2, 3].some(eagle => [3, 4, 5].includes(eagle)); // true, as 3 can fly in both arrays

This little gem returns true if any eagle (representing an array element, but we like to keep things fun here ๐Ÿฆ…) from array1 enjoys the scenery in array2, and false otherwise.

Understanding the mechanics

Taking the deep dive, let's explore the machinery under the hood. some cruises along array1, and for each stop, includes scans array2. So, it's two birds, one stone, or as coders say, a nested iteration leading to O(n * m) complexity where n and m represent the good times enjoyed by array1 and array2.

Embracing the power of short cuts

Anyone loves shortcuts, right? some method is no exception. It short-circuits at the first truthy result, which means if an eagle from array1 finds its twin in array2, the search hits the brakes. It's an O(1) complexity party, bringing a significant lift-off to performance.

Dealing with all sorts of arrays

Just like driving (or flying), you need to expect all sorts of traffic. some and includes have got your back handling arrays with:

  • A mixed bag of data types
  • Sparse arrays touring empty slots
  • Non-primitive elements like the objects and functions

Digging out all common elements

Hunting for all the intersections? Combine filter with includes for that:

const intersections = array1.filter(item => array2.includes(item)); // Now intersections equals [3], 3 found its vehicle in both arrays!

This will give you a new array with all the eagles that could navigate through both array1 and array2.

The visual story

Time to print the pixel story. Imagine checking if a pedestrian shares any paths of a bustling intersection:

Array 1 (๐Ÿšถโ€โ™‚๏ธ): [๐Ÿ”ด, ๐Ÿ”ต, ๐ŸŸข] Array 2 (๐Ÿš—): [๐ŸŸก, ๐Ÿ”ต, ๐ŸŸฃ]

Our movie plot: Watch out for shared paths across the intersection!

const commonPath = Array1.some(el => Array2.includes(el));

Does our pedestrian (๐Ÿšถโ€โ™‚๏ธ) risk being hit by a car (๐Ÿš—)?

๐Ÿšถโ€โ™‚๏ธ (almost) ๐Ÿ’ฅ ๐Ÿš—: [๐Ÿ”ต] // No insurance claims today! The pedestrian and driver shared the blue path without disaster!

Spoiler alert: Intersection Detected! ๐Ÿšฆ๐Ÿ‘Œ

Extra avenues to explore

Handling gridlock traffic

With large arrays, the some and includes tour can get busy. To avoid jam, turn array2 into a Set. Its has method can adapt to heavy traffic by usually offering O(1) time complexity:

const array2Set = new Set(array2); // Better roads, I guess const sharedElementExists = array1.some(eagle => array2Set.has(eagle)); // Now, that's "Fast and Furious".

Library resources

Beyond native JavaScript, libraries like Lodash or Underscore.js offer intersection() methods. These libraries provide optimized, efficient roadmaps and sometimes, much better radio channels.

Guarding against unknown roads

Make sure your function can handle uncharted territories such as null or undefined values and arrays with different lengths. Beyond avoiding bumps on the road, itโ€™ll keep your behind-the-wheel rating high.