How to Create an Array using Intersection of two Arrays in JavaScript?


The intersection of two arrays in JavaScript can be done in different ways, such as using the Set, spread operator, filter() method, or the includes() method. Each method has its own advantages and disadvantages, and it is important to consider which method works best for the given task. The intersection of two arrays is helpful if you want to create a new array that contains only the elements found in both arrays.

Let’s have an example −

arr1 = [ 2, 5, 7, 9, 11, 13, 15, 17 ]
arr2 = [ 1, 3, 5, 7, 11, 13, 16, 17 ]

intersecArr = [ 5, 6, 11, 13, 17 ]

Above we have defined two arrays arr1 and arr2, including some same values existing in both arrays. The intersection of two arrays is antersecArr.

Let’s discuss these approaches to create an array using the intersection of two arrays in JavaScript.

Approach 1: Using filter() and includes() Methods

We can use the filter() and includes() methods to perform the intersection on two arrays. The filter() method accepts a function as its argument and applies it to each element in the array. The function should return a boolean, true or false, indicating whether the element should be included in the new array. In our case, we want the elements present in both input arrays, so we will use the includes() method to check if the element is present in the other array.

Syntax

Below is the syntax for using filter() and include() methods to create a new array using the intersection of two arrays −

let intersection = arr1.filter(x => arr2.includes(x));

The filter() method accepts a callback function as its argument. This callback function is applied to each element of the first array (arr1) and it checks if the current element (x) is present in the second array (arr2) using the includes() method. If the current element (x) is present in the second array (arr2), it is included in the new array (intersection).

If the current element (x) is not present in the second array (arr2), it is excluded from the new array (intersection). The final result is a new array (intersection) containing only the elements present in arr1 and arr2.

Example

In the below example, we create two arrays, arr1, and arr2, each having five elements, of which three are same. Then use the filter and include methods to create a new array of the common elements in both arrays.

<html>
<head>
   <title>Creating an Array using Intersection of two Arrays using Filter() and Includes() methods</title>
</head>
<body>
   <p id="arr1"></p>
   <p id="arr2"></p>
   <p id="result"></p>
   <script>
      let arr1 = [5, 6, 8, 11, 15];
      let arr2 = [3, 5, 8, 11, 17];
            
      document.getElementById("arr1").innerHTML = "Array 1: " + JSON.stringify(arr1);
      document.getElementById("arr2").innerHTML = "Array 1: " + JSON.stringify(arr2);
            
      const intersection = arr1.filter(x => arr2.includes(x));

      document.getElementById("result").innerHTML = "Intersection of Array1 & Array 2: " + JSON.stringify(intersection);
   </script>
</body>
</html>

The above code will create a new array, intersectionArray, that contains only the elements that were present in both of the input arrays.

Approach 2

In this approach, we first create a new set object from elements of arr1. It removes any duplicate elements. Then convert the set object to array using spread operator. This array has no duplicate element. Now we use filter() and include() methods to perform intersection. The further process is the same as in the first approach.

let intersection = [...new Set(arr1)].filter(x => arr2.includes(x));

The above syntax creates a new array "intersection". It contains elements present in arr1 and arr2, after removing any duplicates from arr1.

Example

<html>
<head>
   <title>Creating an Array using Intersection of two Arrays using Spread Operator and Filter() method</title>
</head>
<body>
   <p id="arr1"></p>
   <p id="arr2"></p>
   <p id="result"></p>
   <script>
      let arr1 = [4, 8, 12, 16, 20, 28];
      let arr2 = [8, 16, 20, 24, 28, 30];

      document.getElementById("arr1").innerHTML = "Array 1: " + JSON.stringify(arr1);
      document.getElementById("arr2").innerHTML = "Array 1: " + JSON.stringify(arr2);
        
      let intersection = [...new Set(arr1)].filter(x => arr2.includes(x));

      document.getElementById("result").innerHTML = "Intersection of Array1 & Array 2: " + JSON.stringify(intersection);

   </script>
</body>
</html>

Approach 3: Using Set

In this approach, first, we convert arrays into a set using the new Set() constructor. Then iterate over the second set’s elements using the for...of loop. Then 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 intersection array using the push() method.

Example

<html>
<head>
   <title>Creating an Array using Intersection of two Arrays using Set</title>
</head>
<body>
   <p id="arr1"></p>
   <p id="arr2"></p>
   <p id="result"></p>
   <script>
      function doIntersection(arr1, arr2) {
         const setFirst = new Set(arr1);
         const setSecond = new Set(arr2);
         let intersection = [];
         for (let i of setSecond) {
            if (setFirst.has(i)) {
               intersection.push(i);
            }
         }
         return intersection;
      }

      const arrFirst = [4, 6, 8, 10, 12];
      const arrSecond = [4, 5, 8, 12, 15];

      document.getElementById("arr1").innerHTML = "Array 1: " + JSON.stringify(arrFirst);
      document.getElementById("arr2").innerHTML = "Array 1: " + JSON.stringify(arrSecond);

      const interResult = doIntersection(arrFirst, arrSecond);

      document.getElementById("result").innerHTML = "Intersection of Array1 & Array 2: " + JSON.stringify(interResult);
   </script>
</body>
</html>

In this tutorial, we discussed three approaches to creating an array using the intersection of two arrays with the help of examples. In the first approach, we use filter() and include() methods, while in the second approach, we use the spread operator and Set in addition to filter and include. In the third approach, we created a custom function to perform this task.

Updated on: 23-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements