Write a function to find the intersection of two arrays.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
The most efficient approach uses a Set for fast lookups.
1. Convert one array to a Set for O(1) average time complexity on lookups.
2. Iterate through the second array.
3. For each element in the second array, check if it exists in the Set.
4. If it does, add it to a result array. To avoid duplicates in the result, wrap the result in a Set and convert back to an array.
function intersection(arr1, arr2) {
const set1 = new Set(arr1);
const result = [];
for (const element of arr2) {
if (set1.has(element)) {
result.push(element);
}
}
// To ensure the result has unique values
return [...new Set(result)];
}
const arrayA = [1, 2, 3, 4, 5];
const arrayB = [4, 5, 6, 7, 8];
console.log(intersection(arrayA, arrayB)); // [4, 5]