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
JavaScript Array: Checking for multiple values
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.
Example
The code for this will be ?
const arr1 = [34, 78, 89];
const arr2 = [78, 67, 34, 99, 56, 89];
const multipleIncludes = (first, second) => {
const indexArray = first.map(el => {
return second.indexOf(el);
});
return indexArray.indexOf(-1) === -1;
}
console.log(multipleIncludes(arr1, arr2));
Output
The output in the console ?
true
How It Works
The function maps each element from the first array to its index position in the second array using indexOf(). If an element doesn't exist, indexOf() returns -1. Finally, we check if any -1 exists in the index array.
Alternative Method: Using every()
A more readable approach uses the every() method:
const arr1 = [34, 78, 89];
const arr2 = [78, 67, 34, 99, 56, 89];
const multipleIncludes = (first, second) => {
return first.every(element => second.includes(element));
}
console.log(multipleIncludes(arr1, arr2));
console.log(multipleIncludes([1, 2, 3], [2, 3, 4])); // false - 1 is missing
true false
Comparison
| Method | Readability | Performance |
|---|---|---|
map() + indexOf() |
Less readable | Creates intermediate array |
every() + includes() |
More readable | Stops on first false |
Conclusion
Both methods work effectively for checking multiple values. The every() approach is more readable and potentially faster since it stops execution on the first missing element.
Advertisements
