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

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay