How to Get Intersection of Two Arrays in JavaScript

How to Get Intersection of Two Arrays in JavaScript

Ferenc Almasi β€’ 2021 January 27 β€’ πŸ“– 2 min read

To get the difference of two arrays in JavaScript, you can use the combination of filter and includes. Imagine you have the following two arrays and you want to find out which elements are included in both:

const veggies = ['πŸ…', 'πŸ₯•', 'πŸ₯’'];
const fruits  = ['πŸ“', '🍌', 'πŸ…'];
Copied to clipboard!

To get their intersection, you can use the following call:

const intersection = veggies.filter(v => fruits.includes(v));
Copied to clipboard!

To get their differencem eg.: only the ones that veggies include, you can do the following:

const difference = veggies.filter(v => !fruits.includes(v));
const difference = fruits.filter(f => !veggies.includes(f));
Copied to clipboard!

And in order to get the symmetric difference of two arrays β€” meaning leave out the ones that are in both arrays β€” you need to filter both of them and either use concat or destructuring:

const symmetricDifference = [
    ...veggies.filter(v => !fruits.includes(v)),
    ...fruits.filter(f => !veggies.includes(f))
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Reusable functions

If you need to rely on the same logic multiple times in your codebase, you can reuse them with the following function calls:

const intersect  = (a, b) => a.filter(a => b.includes(a));
const difference = (a, b) => a.filter(a => !b.includes(a));
const symmetric  = (a, b) => [
    ...a.filter(a => !b.includes(a)),
    ...b.filter(b => !a.includes(b))
Copied to clipboard!
How to Get Intersection of Two Arrays in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Why Do You Need to Know About Functional Programming?


Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro