Compare and fill arrays - JavaScript


We are required to write a function that compares two arrays and creates a third array filling that array with all the elements of the second array and filling null for all those elements that are present in the first array but misses out in the second array.

For example −

If the two arrays are −

const arr1 = ['f', 'g', 'h'];
const arr2 = ['f', 'h'];

Then the output should be −

const output = ['f', null, 'h'];

Example

Following is the code −

const arr1 = ['f', 'g', 'h'];
const arr2 = ['f', 'h'];
const compareAndFill = (arr1, arr2) => {
   let offset = 0;
   const res = arr1.map((el, i) => {
      if (el === arr2[offset + i]) {
         return el;
      };
      offset--;
      return null;
   });
   return res;
};
console.log(compareAndFill(arr1, arr2));

Output

This will produce the following output on console −

[ 'f', null, 'h' ]

Updated on: 01-Oct-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements