Simplest code for array intersection in JavaScript
Intersection of two arrays in a single line with filter()
and includes()
. Fast, modern, and slick:
The film star
of our show, filter()
, sweeps through each element in array1
, while includes()
, the assistant director
, checks if an element also exists in array2
. The result? A beautifully curated list of shared items!
The deep behind-the-scenes tour
Let's get to know our stars and supporting cast a little better. Tackle compatibility and performance issues with practical alternatives and understand the nuances of working with objects.
Browser compatibility and performance tuning
Every star shines, but not in all environments. For those not compatible with ES6 features like includes
, bring in its understudy, indexOf
:
Working with big data? Consider using Set
to bring array2
's performance up a notch:
The life of an object in an array
Objects in arrays lead lives more complex than the common data type:
-
Multiplicity of selves: When using
includes()
orindexOf()
, objects are compared by reference. "Are you...me?" — the object asks itself. It shakes itshead{id}
in confusion.To see beyond the façade and compare actual object content, tap into the power of
some()
:
All the world's a stage: alternates for intersection
-
Sorted array shootout: Keep your arrays in order. Use indices to navigate through the chaos and reach intersection gold:
-
Duplicates are bloopers: Banish duplicates from your intersection results. Call in the
Set
, your very own duplo-buster!
Performance under the spotlight
Can't decide what's best for performance? Go through jsperf.com/array-intersection-comparison for performance benchmarks. Make your script's Oscar moment happen!
Signing off: efficiency and simplicity
Performance and simplicity can often pull your script in opposite directions. Here's the low-down:
- Understand and balance between efficiency vs. simplicity. Intersect at your own terms.
- Gain code clarity with arrow functions, but watch out for their side-eye at cross-browser compatibility.
So, whether you're after a one-liner masterpiece or a sorted array saga, make sure it serves your use case.
Was this article helpful?