Getting the intersection of two arrays

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]

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.