Simplest code for array intersection in JavaScript

What’s the simplest way to find the intersection between two arrays in JavaScript without using any external libraries? I’m just trying to write something like:

intersection([1, 2, 3], [2, 3, 4, 5])

And get the result: [2, 3]

Just looking for a clean and readable way to handle javascript array intersection. Any tips?

Hey, I’ve done quite a few small projects where performance wasn’t the main concern, and honestly, this simple one-liner does the trick for basic needs:

const intersection = (a, b) => a.filter(value => b.includes(value));

This is a great way to get a clean and readable javascript array intersection - super straightforward and easy to understand. Perfect for small arrays or quick scripts where simplicity matters more than speed.

Adding onto that, I’ve found that if you’re dealing with larger arrays or want a bit more efficiency, it’s neat to use a Set for quicker lookups. The idea is still simple and keeps your code clean:

const intersection = (a, b) => {
  const setB = new Set(b);
  return a.filter(x => setB.has(x));
};

This method still nails the javascript array intersection in a very readable way, but it’s more performant because checking membership in a Set is faster than using includes, especially as the arrays grow.

Totally agree with what’s been shared here - sometimes the simplest approach is the best, especially for everyday use. Honestly, I used to overthink these things too, but for most cases, that Set-based filter method balances clarity and speed nicely.

The beauty of JavaScript is how clean your code can stay while handling javascript array intersection elegantly. Whether you’re writing quick frontend code or lightweight personal scripts, this pattern keeps your codebase understandable and maintainable.