JavaScript – Find the Intersection of Two Arrays

In this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays.

The problem

Write a function to find the intersection of two arrays (i.e., common elements).

Input

arr1 = [1, 2, 3, 4]
arr2 = [2, 4, 6, 8]

Output

[2, 4]

The Solution

function intersection(arr1, arr2) {
  // Convert one of the arrays into a Set to allow efficient lookup
  const set1 = new Set(arr1);
  
  // Use the filter method to find common elements between the two arrays
  return arr2.filter(num => set1.has(num));
}

// Test the function
const arr1 = [1, 2, 3, 4];
const arr2 = [2, 4, 6, 8];
console.log(intersection(arr1, arr2)); // Output: [2, 4]

In the above example, we first convert arr1 into a Set. A Set allows us to check whether an element exists with an average time complexity of O(1). We then use the filter method on arr2 to only include elements that exist in set1. This gives us the intersection.The function returns an array of the common elements.

Similar Reads