DEV Community

Cover image for Array intersection
chandra penugonda
chandra penugonda

Posted on

Array intersection

Can you write a function that takes two arrays as inputs and returns to us their intersection? Let's return the intersection in the form of an array.

function intersection(arr1, arr2) {

}

const nums1 = [4, 9, 5];
const nums2 = [9, 4, 9, 8, 4];

console.log(intersection(nums1, nums2)); // [9,4] or [4,9]
Enter fullscreen mode Exit fullscreen mode

Solution 1

function intersection(arr1, arr2) {
  const set = new Set(arr1);
  return [...new Set(arr2.filter((num) => set.has(num)))];
}

const nums1 = [4, 9, 5];
const nums2 = [9, 4, 9, 8, 4];

console.log(intersection(nums1, nums2)); // [9,4]
Enter fullscreen mode Exit fullscreen mode

Solution 2

function intersection(arr1, arr2) {
  const set = new Set();
  for (const num of arr1) {
    set.add(num);
  }
  const result = [];
  for (const num of arr2) {
    if (set.has(num)) {
      result.push(num);
      set.delete(num);
    }
  }
  return result;
}

const nums1 = [4, 9, 5];
const nums2 = [9, 4, 9, 8, 4];

console.log(intersection(nums1, nums2)); // [9,4]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)