Exercise 12: Find Common Elements in Two Arrays
Problem Statement
Create a function `commonElements(arr1, arr2)` that returns common elements in both arrays.
Example: commonElements([1, 2, 3], [2, 3, 4]) → [2, 3]
Sample Output:
commonElements([1, 2, 3], [2, 3, 4]) => [2, 3] commonElements(["a", "b"], ["b", "c"]) => ["b"]
Solution
const commonElements = (arr1, arr2) => {
const set2 = new Set(arr2);
return [...new Set(arr1)].filter(item => set2.has(item));
};Explanation
Overall Goal:
- Dono arrays me common elements find karna.
Line 1: Function header
const commonElements = (arr1, arr2) => {
Line 2: Create set
const set2 = new Set(arr2);- Fast lookup ke liye.
Line 3: Filter common
return [...new Set(arr1)].filter(item => set2.has(item));- arr1 me se wo items filter jo set2 me hain.
Real world:
- Data comparison: common items.
- Set operations: intersection.