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 ]
Updated on: 2020-08-24T06:09:43+05:30

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements