Compare two arrays of single characters and return the difference? JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to compare, and get the difference, between two arrays containing single character strings appearing multiple times in each array.

Example of two such arrays are −

const arr1 = ['A', 'C', 'A', 'D'];
const arr2 = ['F', 'A', 'T', 'T'];

We will check each character at the same position and return only the parts who are different.

Example

const arr1 = ['A', 'C', 'A', 'D'];
const arr2 = ['F', 'A', 'T', 'T'];
const findDifference = (arr1, arr2) => {
   const min = Math.min(arr1.length, arr2.length);
   let i = 0;
   const res = [];
   while (i < min) {
      if (arr1[i] !== arr2[i]) {
         res.push(arr1[i], arr2[i]);
      };
      ++i;
   };
   return res.concat(arr1.slice(min), arr2.slice(min));
};
console.log(findDifference(arr1, arr2));

Output

And the output in the console will be −

[
   'A', 'F', 'C',
   'A', 'A', 'T',
   'D', 'T'
]
raja
Published on 23-Nov-2020 06:48:09
Advertisements