Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check whether multiple values exist within a JavaScript array
We are required to write a JavaScript function that takes in two arrays of Numbers and checks whether all the elements of the first array exist in the second or not.
Following are our arrays ?
const arr1 = [34, 78, 89]; const arr2 = [78, 67, 34, 99, 56, 89];
Let's write the code and check for multiple values ?
Using indexOf() Method
const arr1 = [34, 78, 89];
const arr2 = [78, 67, 34, 99, 56, 89];
const contains = (first, second) => {
const indexArray = first.map(el => {
return second.indexOf(el);
});
return indexArray.indexOf(-1) === -1;
}
console.log(contains(arr1, arr2));
true
Using every() Method (Recommended)
A more elegant approach uses the every() method to check if all elements exist:
const arr1 = [34, 78, 89];
const arr2 = [78, 67, 34, 99, 56, 89];
const containsAll = (first, second) => {
return first.every(element => second.includes(element));
}
console.log(containsAll(arr1, arr2));
console.log(containsAll([1, 2, 3], [1, 2])); // false - 3 is missing
true false
Using Set for Better Performance
For larger arrays, converting the second array to a Set improves lookup performance:
const arr1 = [34, 78, 89];
const arr2 = [78, 67, 34, 99, 56, 89];
const containsAllOptimized = (first, second) => {
const set = new Set(second);
return first.every(element => set.has(element));
}
console.log(containsAllOptimized(arr1, arr2));
true
Comparison
| Method | Time Complexity | Readability | Best For |
|---|---|---|---|
map() + indexOf() |
O(n × m) | Medium | Small arrays |
every() + includes() |
O(n × m) | High | Most cases |
every() + Set |
O(n + m) | Medium | Large arrays |
Conclusion
Use every() with includes() for readable code, or combine with Set for better performance with large arrays. The every() method provides the most intuitive approach to check if all elements exist.
Advertisements
