Getting the intersection of two arrays

Posted on

To find which elements appear in both of two arrays, walk through every element in the first array and check if it exists in the second. With Array.prototype.filter() and Array.prototype.includes(), we can do that in a single line.

const getIntersection = (first, second) => {
  return first.filter(element => second.includes(element))
}
 
getIntersection([6, 15, 19, 86, 4], [4, 19, 22, 92, 51, 37])
// ⇒ [19, 4]
const getIntersection = (first, second) => {
  return first.filter(element => second.includes(element))
}
 
getIntersection([6, 15, 19, 86, 4], [4, 19, 22, 92, 51, 37])
// ⇒ [19, 4]
Debug
none
Grid overlay