Return a sorted array in lexicographical order in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes two arrays, say arr1 and arr2. Our function should return a sorted array in lexicographical order of the strings of arr1 which are substrings of strings of arr2.

Example

The code for this will be −

const lexicographicalSort = (arr1 = [], arr2 = []) => {
   let i, j;
   const res = [];
   outer: for (j = 0; j < arr1.length; j++) {
      for (i = 0; i < arr2.length; i++) {
         if (arr2[i].includes(arr1[j])) {
            res.push(arr1[j]);
            continue outer;
         };
      };
   }
   return res.sort();
};
const arr2 = ["lively", "alive", "harp", "sharp", "armstrong"];
const arr1 = ["xyz", "live", "strong"];
console.log(lexicographicalSort(arr1, arr2));

Output

And the output in the console will be −

[ 'live', 'strong' ]
raja
Published on 24-Nov-2020 09:55:48
Advertisements