Explain Codes LogoExplain Codes Logo

Simplest code for array intersection in JavaScript

javascript
array-intersection
performance-benchmarking
javascript-performance
Nikita BarsukovbyNikita Barsukov·Sep 26, 2024
TLDR

Intersection of two arrays in a single line with filter() and includes(). Fast, modern, and slick:

const intersection = array1.filter(value => array2.includes(value));

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:

// just like in the prequel, ES5 const intersection = array1.filter(value => array2.indexOf(value) !== -1);

Working with big data? Consider using Set to bring array2's performance up a notch:

// Set; the hotshot new kid on the block const setB = new Set(array2); const intersection = array1.filter(value => setB.has(value));

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() or indexOf(), objects are compared by reference. "Are you...me?" — the object asks itself. It shakes its head{id} in confusion.

    const objectArray1 = [{ id: 1 }, { id: 2 }]; const objectArray2 = [{ id: 1 }, { id: 2 }]; const intersection = objectArray1.filter(obj => objectArray2.includes(obj)); // Even they don't understand themselves. Intersection is []

    To see beyond the façade and compare actual object content, tap into the power of some():

    const intersection = objectArray1.filter(obj1 => objectArray2.some(obj2 => obj1.id === obj2.id) // Even John and Jane Doe have unique IDs! );

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:

    function intersectSortedArrays(a, b) { let ai = 0, bi = 0; const intersection = []; while (ai < a.length && bi < b.length) { // "Ai and Bi walk into a bar..." (complete the joke) // Result? A sorted array intersection in O(n)! if (a[ai] < b[bi]) {ai++;} else if (a[ai] > b[bi]) {bi++;} else { // "And hilarity ensues!" intersection.push(a[ai]); ai++; bi++; } } return intersection; }
  • Duplicates are bloopers: Banish duplicates from your intersection results. Call in the Set, your very own duplo-buster!

    const intersection = [...new Set(array1)].filter(value => array2.includes(value)); // Because why settle for "Titanic 2" when you can have "Titanic"?

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.