JavaScript Program To Perform Intersection Between Two Arrays
When working with arrays in JavaScript, you may need to find the common elements between two arrays. This process is known as performing an intersection operation. In this guide, we will cover everything you need to know about performing an intersection operation between two arrays using JavaScript.
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Perform Intersection Between Two Arrays Using Set
In the code given below, an intersection is performed between two arrays, array1
and array2
.
A JavaScript Set is a collection of unique values. Each value can only occur once in a Set.
The has() method returns a boolean indicating whether an element with the specified value exists in a Set object or not.
- The array elements are converted into
Set
elements using the new Set()
constructor.
- The
for...of
loop is used to iterate over the second Set
elements.
- The
has()
method is used to check if the element is in the first Set
.
- If the element is present in the first
Set
, that element is added to the intersectionResult array using the push()
method.
// JavaScript Program to perform intersection between two arrays using Set
function setIntersection(arr1, arr2) {
// converting into Set
const sA = new Set(arr1);
const sB = new Set(arr2);
let intersectionResult = [];
for (let i of sB) {
if (sA.has(i))
intersectionResult.push(i);
}
return intersectionResult;
}
const arr1 = [4, 2, 3, 5, 9, 12, 14];
const arr2 = [4, 3, 5, 8];
const res = setIntersection(arr1, arr2);
console.log(res);
[ 4, 3, 5 ]
Perform Intersection Between Two Arrays Using filter() Method
In the code given below, an intersection is performed between two arrays using the filter()
method. The filter method iterates over an array and returns the array elements that pass the given condition.
- Each element of the first array is compared with the second array using the
indexOf()
method.
- The
arr2.indexOf(x)
method searches arr2 and returns the position of the first occurrence of arr1. If the value cannot be found, it returns -1.
- All the elements that are in both arrays are returned by the
filter()
method.
// JavaScript Program to perform intersection between two arrays
function setIntersection(arr1, arr2) {
const intersectionResult = arr1.filter(x => arr2.indexOf(x) !== -1);
return intersectionResult;
}
const array1 = [1, 2, 3, 5, 9];
const array2 = [1, 3, 5, 8];
const res = setIntersection(array1, array2);
console.log(res);
[ 1, 3, 5 ]
Conclusion
In conclusion, performing an intersection operation between two arrays is a common task in JavaScript, and there are multiple ways to achieve it. Whether you choose to use the filter method or the Set object, it is important to consider the size of the arrays and the efficiency of each method.