Simplest code for array intersection in javascript
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The simplest array intersection in JavaScript is usually filter() plus includes(). That answer is easy to read and perfectly fine for small arrays, but once performance or duplicate handling matters, a Set-based approach is usually better.
The Readable Version
Output:
This is often the best answer when the arrays are short and clarity matters more than optimization.
Why It Can Be Slow
includes() scans the target array each time, so filter + includes is roughly O(m * n) for arrays of sizes m and n. That is fine for small lists, but it gets expensive if both arrays are large.
Faster Version with Set
This reduces the lookup cost dramatically because Set.has() is typically near constant time. The total work becomes closer to O(m + n).
Unique Intersection
Sometimes you want unique common values rather than repeated matches:
A slightly better version avoids rebuilding the set:
This detail matters because "intersection" is ambiguous until you decide what duplicates should mean.
Objects Are Different
These simple patterns compare primitives by value, but objects compare by reference. Two separate objects with the same fields are not equal to includes() or Set.has() unless they are literally the same object reference.
So if you need intersection by object property, map to a key first:
Choosing the Right Version
Use filter + includes when:
- the arrays are small
- readability matters most
- duplicates should be preserved naturally
Use Set when:
- arrays are large
- membership checks are frequent
- performance matters
Another important choice is whether order should be preserved. The simple filter patterns preserve the order of the first array, which is often useful in UI and business logic. A mathematically correct intersection that returns values in an unexpected order can still be the wrong answer for the application.
That practical detail matters more often than people expect.
Order-sensitive UI code is a common example.
So is report generation.
Ordering requirements matter in both.
That point is easy to miss.
Common Pitfalls
- Using
includes()on large arrays and wondering why it is slow. - Rebuilding the same
Setrepeatedly inside the filter callback. - Forgetting to define whether duplicates should be kept.
- Assuming object values compare by content instead of reference.
- Choosing a clever one-liner before deciding what semantics you actually need.
Summary
- '
filter + includesis the simplest readable intersection pattern.' - '
Setis usually the better choice for larger arrays.' - Decide whether duplicates should be preserved or removed.
- Primitive and object intersections behave differently.
- The best solution depends on clarity, scale, and equality semantics.

