Open In App

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

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:






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:




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:




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 ]

Article Tags :