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 −


const master = [3,9,11,2,20];
const keys = [1,2,3];
const prepareBooleans = (master, keys) => {
   const booleans = => {
      return keys.includes(el);
   return booleans;
console.log(prepareBooleans(master, keys));


The output in the console will be −

[ true, false, false, true, false ]

Updated on: 24-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started