Was it helpful?

Question

Compare and fill arrays - 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'];

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' ]
raja
Published on 01-Oct-2020 14:08:44
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top