How to Get Intersection of Two Arrays in JavaScript

How to Get Intersection of Two Arrays in JavaScript

Ferenc Almasi β€’ 2021 January 27 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

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:

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

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

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

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

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

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:

Copied to clipboard!
const symmetricDifference = [
    ...veggies.filter(v => !fruits.includes(v)),
    ...fruits.filter(f => !veggies.includes(f))
];
symmetric-difference.js

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:

Copied to clipboard! Playground
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))
];
diff.js
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?

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.