Check if an array contains any element of another array in JavaScript
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In JavaScript, checking if an array contains any element of another array is a common task that can be approached in various ways depending on performance needs, readability, and specific requirements. We'll explore different methods including using loops, the includes() method, and the newer Set object.
1. Using Array.prototype.includes()
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. By combining this with the some() method, which tests whether at least one element in the array passes the test implemented by the provided function, you can easily check if any element of one array exists in another.
2. Using Loops
For cases where older browser support is required, or when a more manual approach is preferred, you can use nested loops to check for the presence of elements:
3. Using Set
The Set object lets you store unique values. Since it's built for fast access, converting an array to a set and then checking if any element of the second array exists can be efficient, especially for large arrays with unique elements.
Comparison Table
| Method | Best Usage Case | Performance | Browser Compatibility |
| includes() + some() | Small to medium arrays, readability preferred | Good for smaller datasets | ES6+ (not IE) |
| Nested loops | High compatibility needs, all browsers | Slower especially for large arrays | All browsers |
| Set + some() | Large datasets with unique elements | Fast for look-ups, slow for initial creation | ES6+ (not IE) |
Best Practices and Considerations
- Performance: Consider the size of your arrays. Nested loops have a time complexity of where n and m are the lengths of the two arrays.
Setandincludes()have better average-case time complexities in scenarios with larger datasets. - Browser Support: If you need to support older browsers like Internet Explorer, avoid newer ES6 methods unless you're transpiling your code.
- Readability: Using high-level functions like
includes()andsome()can make your code easier to read and maintain compared to manual loops.
Conclusion
Selecting the right approach depends on specific case needs such as performance requirements and environment limitations. In modern web development, leveraging built-in high-order functions like includes() and some() or utilizing the Set object provides efficient and concise solutions. However, understanding all available methods allows for greater flexibility and adaptability in your programming.

