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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object