← Back to libraryQuestion 168 of 468
🧩JavaScript CodingBeginner

Intersection of Two Arrays

📌 Definition:

Return the values that appear in both arrays (e.g. [1,2,3] and [2,3,4] -> [2,3]).

📖 Detailed Explanation:

Put one array into a Set for O(1) lookups, then filter the other array by membership. Wrap in a Set again if you must dedupe the result.

💻 Solutions:
function intersection(a, b) {
  const setB = new Set(b);
  return [...new Set(a)].filter((x) => setB.has(x));
}
🔑 Key Points:
  • Set gives O(1) membership → overall O(n+m)
  • Dedupe inputs/outputs with Set as needed
  • Nested filter+includes would be O(n*m) — avoid for large arrays
  • Order follows the first array
🌍 Real-World Example:

Intersection compares expected vs actual result sets in tests, or finds users who belong to two cohorts for a targeted check.

🎯 Scenario-Based Interview Question:

a.filter(x => b.includes(x)) is correct but times out on two 50k-element arrays. Why, and what is the fix?