DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 78

The task is to find the intersection given two arrays.

The boilerplate code

function getIntersection(arr1, arr2) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Loop through the other array and check if the item exists

for(const item of arr2) {
if(set.has(item)) {
result.add(item)
}
}
Enter fullscreen mode Exit fullscreen mode

Store the results in another set to avoid duplicate intersections

return[...result]
Enter fullscreen mode Exit fullscreen mode

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];
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)