JavaScript Answers

How to Compute the Intersection of Two Arrays in JavaScript?

Spread the love

To compute the intersection of two arrays in JavaScript, we can use the array filter method with the includes method to get the elements that are in both arrays and return them in an array.

For instance, we can write:

const arr1 = ["mike", "sue", "tom", "kathy", "henry"];
const arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];

const result = arr1.filter((n) => {
  return arr2.includes(n);

to get all the name strings that are in both arr1 and arr2 by calling arr1.filter with a callback that returns the condition that the items are also included with arr2 with arr2.includes(n) .

Then we assign the returned result to result .

Therefore, result is [“sue”, “kathy”] .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.