Check if an array contains any element of another array in JavaScript
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.
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:
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:
Our movie plot: Watch out for shared paths across the intersection!
Does our pedestrian (๐ถโโ๏ธ) risk being hit by a car (๐)?
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:
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.
Was this article helpful?