Comparing and filling arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 −

Example

The code for this will be −

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

The output in the console will be −

[ 'f', null, 'h' ]
raja
Published on 24-Oct-2020 12:14:47
Advertisements