How to Create an Array using Intersection of two Arrays in JavaScript ? (original) (raw)

Last Updated : 21 May, 2024

In this article, we will try to understand how to create an array using the intersection values of two arrays in JavaScript using some coding examples.

**For Example:

arr1 = [1, 3, 5, 7, 9, 10, 14, 15]
arr2 = [1, 2, 3, 7, 10, 11, 13, 14]

result_arr = [1, 3, 7, 10, 14]

**Approach 1:

**Example:

JavaScript `

let first_array = [1, 3, 5, 7, 9]; let second_array = [2, 3, 4, 5, 6, 9];

let res_arr = (first_array, second_array) => { let new_array = []; for (let i = 0; i < first_array.length; i++) { for (let j = 0; j < second_array.length; j++) { if (first_array[i] === second_array[j]) { new_array.push(first_array[i]); } } } return new_array; };

console.log("Array obtained is :"); console.log(res_arr(first_array, second_array));

`

**Output:

Array obtained is :
[ 3, 5, 9 ]

**Approach 2:

**Example:

JavaScript `

let first_array = [1, 3, 5, 7, 9]; let second_array = [2, 3, 4, 5, 6, 9];

let new_array = first_array.filter( (element) => second_array.includes(element));

console.log("Array obtained is :"); console.log(new_array);

`

**Output:

Array obtained is :
[ 3, 5, 9 ]

**Approach 3:

**Example:

JavaScript `

let res_arr = (arr1, arr2) => { let first_array_set = new Set(arr1); let second_array_set = new Set(arr2); let new_array = []; for (let element of second_array_set) { if (first_array_set.has(element)) { new_array.push(element); } } return new_array; };

let first_array = [1, 3, 5, 7, 9]; let second_array = [2, 3, 4, 5, 6, 9];

console.log("Array obtained is: "); console.log(res_arr(first_array, second_array));

`

**Output:

Array obtained is:
[ 3, 5, 9 ]

Using reduce Method

Using the reduce method, iterate through one array, adding elements that are present in both arrays to a new array. Check for element inclusion in the second array using the includes method, effectively creating an array representing their intersection.

**Example: In this example we finds the intersection of two arrays, arr1 and arr2, using the reduce method. It checks if each element in arr1 exists in arr2, collecting common elements into the intersection array.

JavaScript `

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

let intersection = arr1.reduce((acc, curr) => { if (arr2.includes(curr)) { acc.push(curr); } return acc; }, []);

console.log(intersection);

`