Categories
JavaScript Answers

How to check if array has elements from another array with JavaScript?

Spread the love

Sometimes, we want to check if array has elements from another array with JavaScript.

In this article, we’ll look at how to check if array has elements from another array with JavaScript.

How to check if array has elements from another array with JavaScript?

To check if array has elements from another array with JavaScript, we can use the array some and includes method.

For instance, we write:

const a = [1, 2, 3]
const b = [1, 4, 5]
const includesB = a.some(e => b.includes(e))
console.log(includesB)

to call a.some with a callback that returns b.includes(e) to check any element in a is also in b.

Since 1 is in a and b, includesB is true.

Conclusion

To check if array has elements from another array with JavaScript, we can use the array some and includes method.

By John Au-Yeung

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

Leave a Reply

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