The Intersection and difference between two arrays

There are cases when we need to find common elements from two arrays; in such cases we can use the formula

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

taking common elements from array 1 and array 2
If we want to take all elements from array 1 that are not in array2 then you can use this formula.

let difference = array1.filter(x => !array2.includes(x));

This way, you will get an array containing all the elements of array 1 that are not in array 2 and vice-versa.


Leave a comment

Your email address will not be published. Required fields are marked *