JavaScript Program to Find Intersection of Two Arrays
const intersection = arr1.filter(value => arr2.includes(value)); to find the common elements between two arrays in JavaScript.Examples
How to Think About It
Algorithm
Code
const arr1 = [1, 2, 3]; const arr2 = [2, 3, 4]; const intersection = arr1.filter(value => arr2.includes(value)); console.log(intersection);
Dry Run
Let's trace the example arrays [1, 2, 3] and [2, 3, 4] through the code.
Start with first element
Check if 1 (from arr1) is in arr2 [2, 3, 4] → No
Check second element
Check if 2 (from arr1) is in arr2 [2, 3, 4] → Yes, add 2 to result
Check third element
Check if 3 (from arr1) is in arr2 [2, 3, 4] → Yes, add 3 to result
Return result
Result array is [2, 3]
| Element from arr1 | Is in arr2? | Result array |
|---|---|---|
| 1 | No | [] |
| 2 | Yes | [2] |
| 3 | Yes | [2, 3] |
Why This Works
Step 1: Filtering elements
The filter method goes through each element of the first array and keeps only those that pass the test.
Step 2: Checking presence
The test uses includes to see if the current element exists in the second array.
Step 3: Building intersection
Elements passing the test are collected into a new array, which is the intersection.
Alternative Approaches
const arr1 = [1, 2, 3]; const arr2 = [2, 3, 4]; const set2 = new Set(arr2); const intersection = arr1.filter(value => set2.has(value)); console.log(intersection);
const arr1 = [1, 2, 3]; const arr2 = [2, 3, 4]; const intersection = []; for (const val of arr1) { if (arr2.includes(val)) { intersection.push(val); } } console.log(intersection);
const arr1 = [1, 2, 3]; const arr2 = [2, 3, 4]; const intersection = arr1.reduce((acc, val) => { if (arr2.includes(val)) acc.push(val); return acc; }, []); console.log(intersection);
Complexity: O(n * m) time, O(min(n, m)) space
Time Complexity
The main approach uses filter on the first array (size n) and includes on the second array (size m), resulting in O(n * m) time.
Space Complexity
The result array stores at most the smaller array's size elements, so space is O(min(n, m)).
Which Approach is Fastest?
Using a Set for the second array reduces lookup to O(1), improving time to O(n), which is faster for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| filter + includes | O(n * m) | O(min(n, m)) | Small arrays or simple code |
| filter + Set.has | O(n) | O(m) | Large arrays needing speed |
| for loop + includes | O(n * m) | O(min(n, m)) | Beginners learning loops |
| reduce + includes | O(n * m) | O(min(n, m)) | Functional programming style |
includes checks for exact matches and does not handle nested arrays or objects.