Exercise 7: Find Intersection of Multiple Arrays
Problem Statement
Create a function `intersection(...arrays)` that returns common elements in all arrays.
Example: intersection([1, 2, 3], [2, 3, 4], [3, 4, 5]) → [3]
Sample Output:
intersection([1, 2, 3], [2, 3, 4], [3, 4, 5]) => [3] intersection([1, 2], [2, 3], [2, 4]) => [2]
Solution
const intersection = (...arrays) => {
if (arrays.length === 0) return [];
return arrays.reduce((acc, arr) => acc.filter(x => arr.includes(x)));
};Explanation
Overall Goal:
- Multiple arrays me common elements find karna.
Real world:
- Data analysis: common items across datasets.
- Set operations: intersection of multiple sets.