Categories
JavaScript Answers

How to Compute the Intersection of Two Arrays in JavaScript?

Spread the love

Sometimes, we want to compute the intersection of two arrays in JavaScript.

In this article, we’ll look at how to compute the intersection of two arrays in JavaScript.

Compute the Intersection of Two Arrays in JavaScript

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);
});
console.log(result)

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”] .

Conclusion

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.

Leave a Reply

Your email address will not be published. Required fields are marked *