How to find the intersection of two arrays (values that exist in both arrays) in JavaScript

3 Answers

0 votes
const array1 = [1, 2, 6, 3, 9, 5];
const array2 = [5, 6, 7, 10, 11];
 
const intersection = array1.filter(x => array2.includes(x));
 
console.log(intersection);
     
     
     
/*
run:
     
[6, 5]
     
*/
 

 



answered Jan 31, 2021 by avibootz
edited Sep 27 by avibootz
0 votes
const array1 = [1, 2, 6, 3, 9, 5];
const array2 = [5, 6, 7, 10, 11];
 
const intersection = array1.filter(x => array2.indexOf(x) !== -1);
 
console.log(intersection);
     
     
     
/*
run:
     
[6, 5]
     
*/

 



answered Jan 31, 2021 by avibootz
edited Sep 27 by avibootz
0 votes
const arr1 = [5, 7, 1, 1, 6, 0, 2];
const arr2 = [2, 8, 8, 6, 9, 3, 3];
  
const intersection = [...new Set(arr1)].filter(item => arr2.includes(item));
  
console.log(intersection); 
  
   
  
  
/*
run:
  
[ 6, 2 ]
  
*/

 



answered Sep 27 by avibootz
...