Comparing and filling arrays in 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'];

Therefore, let’s write the code for this function −


The code for this will be −

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


The output in the console will be −

[ 'f', null, 'h' ]