
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compare Two Arrays in JavaScript and Create New Boolean Array
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 −
Example
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));
Output
The output in the console will be −
[ true, false, false, true, false ]
Advertisements