How to Find the Intersection and Difference of Two Arrays in JavaScript?

Estimated read time 1 min read

You can find the intersection and difference of two arrays in JavaScript using the filter method and the includes method.

Here’s an example to find the intersection of two arrays:

const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];

const intersection = array1.filter(value => array2.includes(value));
console.log(intersection); // Output: [3, 4]

In this example, the filter method is used to filter the values of array1 based on whether they are included in array2. The includes method is used to check if a value is present in the array.

Here’s an example to find the difference of two arrays:

const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];

const difference = array1.filter(value => !array2.includes(value));
console.log(difference); // Output: [1, 2]

In this example, the filter method is used to filter the values of array1 based on whether they are not included in array2. The ! operator is used to negate the result of the includes method, so that the filter method returns the values that are not present in array2.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply