The task is to find the intersection given two arrays.
The boilerplate code
function getIntersection(arr1, arr2) {
// your code here
}
Since the arrays are not sorted and may contain duplicates, a method of fast lookups and removing duplicates is the right approach. Convert one array into a set
const set1 = new Set(arr1);
const result = new Set();
Loop through the other array and check if the item exists
for(const item of arr2) {
if(set.has(item)) {
result.add(item)
}
}
Store the results in another set to avoid duplicate intersections
return[...result]
The final code
function getIntersection(arr1, arr2) {
// your code here
const set1 = new Set(arr1);
const result = new Set();
for(const item of arr2) {
if(set1.has(item)) {
result.add(item);
}
}
return[...result];
}
That's all folks!
Top comments (0)