Write a JavaScript Program To Perform Intersection Between Two Arrays

In JavaScript, we can find the intersection between two arrays by comparing their elements and returning the common ones.

In this tutorial, we’ll discuss how to perform intersection between two arrays using JavaScript.

Let’s assume we have two arrays, arr1 and arr2, and we want to find their intersection.

We can do this by iterating over one array and checking if each element is present in the other array.

If it is, we add it to a new array, which will contain the intersection of the two arrays.

Here’s a JavaScript program that performs the intersection between two arrays:

function intersection(arr1, arr2) {
  const result = [];
  
  for(let i = 0; i < arr1.length; i++) {
    if(arr2.indexOf(arr1[i]) !== -1 && result.indexOf(arr1[i]) === -1) {
      result.push(arr1[i]);
    }
  }
  
  return result;
}

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

const intersect = intersection(arr1, arr2);

console.log(intersect); // [3, 4, 5]

In this program, we define a function named intersection that takes two arrays, arr1 and arr2, as arguments. We also define a new array named result, which will store the intersection of the two arrays.

Next, we use a for loop to iterate over arr1. Inside the loop, we check if each element in arr1 is present in arr2 using the indexOf method.

If the element is present, we check if it’s already in the result array using the indexOf method again. If it’s not, we add it to the result array using the push method.

Finally, we return the result array, which contains the intersection of the two arrays.

We then define two arrays, arr1 and arr2, and call the intersection function with these arrays as arguments. We store the result in a variable named intersect and log it to the console.

When we run this program, we get the output [3, 4, 5], which is the intersection of arr1 and arr2.

In conclusion, finding the intersection between two arrays in JavaScript is relatively simple.

We can iterate over one array and check if each element is present in the other array, adding the common elements to a new array.

We can then return this new array, which contains the intersection of the two arrays.