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
How to compare two arrays in JavaScript and make a new one of true and false? JavaScript
We have 2 arrays in JavaScript and we want to compare one with the other to see if the elements of master array exists in keys array, and then make one new array of the same length that of the master array but containing only true and false (being true for the values that exists in keys array and false the ones that don't).
Let's say, if the two arrays are ?
const master = [3,9,11,2,20]; const keys = [1,2,3];
Then the final array should be ?
const finalArray = [true, false, false, true, false];
Therefore, let's write the function for this problem ?
Using Array.map() and Array.includes()
The most efficient approach uses map() to transform each element and includes() to check membership:
const master = [3, 9, 11, 2, 20];
const keys = [1, 2, 3];
const prepareBooleans = (master, keys) => {
const booleans = master.map(el => {
return keys.includes(el);
});
return booleans;
};
console.log(prepareBooleans(master, keys));
[ true, false, false, true, false ]
Simplified Version
We can make the function more concise by removing the intermediate variable:
const master = [3, 9, 11, 2, 20];
const keys = [1, 2, 3];
const prepareBooleans = (master, keys) => {
return master.map(el => keys.includes(el));
};
console.log(prepareBooleans(master, keys));
[ true, false, false, true, false ]
Using Set for Better Performance
For large arrays, using a Set provides O(1) lookup time instead of O(n) with includes():
const master = [3, 9, 11, 2, 20];
const keys = [1, 2, 3];
const prepareBooleans = (master, keys) => {
const keySet = new Set(keys);
return master.map(el => keySet.has(el));
};
console.log(prepareBooleans(master, keys));
[ true, false, false, true, false ]
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
Array.includes() |
O(n × m) | Small arrays |
Set.has() |
O(n) | Large arrays |
Conclusion
Use Array.map() with includes() for simple cases. For better performance with large datasets, convert the keys array to a Set first.
