JavaScript Program to Find Common Elements in Two Arrays
const common = arr1.filter(x => arr2.includes(x)); to find common elements in two arrays in JavaScript.Examples
How to Think About It
Algorithm
Code
const arr1 = [1, 2, 3]; const arr2 = [2, 3, 4]; const commonElements = arr1.filter(element => arr2.includes(element)); console.log(commonElements);
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 is in [2, 3, 4] → No
Check second element
Check if 2 is in [2, 3, 4] → Yes, add 2
Check third element
Check if 3 is in [2, 3, 4] → Yes, add 3
Return result
Common elements are [2, 3]
| Element from arr1 | Is in arr2? | Common Elements So Far |
|---|---|---|
| 1 | No | [] |
| 2 | Yes | [2] |
| 3 | Yes | [2, 3] |
Why This Works
Step 1: Filtering the first array
We use filter to go through each element of the first array and decide if it should be kept.
Step 2: Checking presence in second array
For each element, includes checks if it exists in the second array, returning true or false.
Step 3: Collecting common elements
Only elements that return true from includes are kept, forming the array of common elements.
Alternative Approaches
const arr1 = [1, 2, 3]; const arr2 = [2, 3, 4]; const set2 = new Set(arr2); const common = arr1.filter(x => set2.has(x)); console.log(common);
const arr1 = [1, 2, 3]; const arr2 = [2, 3, 4]; const common = []; for (let i = 0; i < arr1.length; i++) { for (let j = 0; j < arr2.length; j++) { if (arr1[i] === arr2[j]) { common.push(arr1[i]); break; } } } console.log(common);
Complexity: O(n * m) time, O(min(n, m)) space
Time Complexity
The main method 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 output array stores common elements, which can be at most the size of the smaller array, so O(min(n, m)) space.
Which Approach is Fastest?
Using a Set for the second array reduces lookup to O(1), making the overall time 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 | O(n) | O(m) | Large arrays needing speed |
| Nested loops | O(n * m) | O(min(n, m)) | Very small arrays or educational purposes |
includes checks for exact matches and may miss duplicates or different types.