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.


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])) {
            continue outer;
   return res.sort();
const arr2 = ["lively", "alive", "harp", "sharp", "armstrong"];
const arr1 = ["xyz", "live", "strong"];
console.log(lexicographicalSort(arr1, arr2));


And the output in the console will be −

[ 'live', 'strong' ]
Updated on 24-Nov-2020 09:56:02