Checking if an array is sorted lexicographically in reference to some scrambled alphabet sequence in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of string words as the first argument. The second argument to the function will be a string containing all 26 English lowercase alphabets but in some random scrambled order.

The task of our function is to check whether the words in the array are placed lexicographically correctly according to the order specified by the second argument. If it is so, we should return true, false otherwise.

For example −

If the input array of words and the order is −

const arr = ['this', 'is', 'something', 'mad'];
const order = 'hdetljnopqabcuvwxfgirsykmz';

Then the output should be −

const output = true;

because 't' comes before 'i' which comes before 's' which comes before 'm' in the order string.

Example

The code for this will be −

 Live Demo

const arr = ['this', 'is', 'something', 'mad'];
const order = 'hdetljnopqabcuvwxfgirsykmz';
const isPlacedCorrectly = (arr = [], order) => {
   const { length } = arr;
   for(let i = 0; i < length - 1; i++){
      for(let j =0; j < arr[i].length;j++){
         if(order.indexOf(arr[i][j])< order.indexOf(arr[i+1][j])) {
            break;
         }
         else if (order.indexOf(arr[i][j]) === order.indexOf(arr[i+1][j])){
            continue;
         } else {
            return false;
         }
      }
   }
   return true;
};
console.log(isPlacedCorrectly(arr, order));

Output

And the output in the console will be −

true
raja
Published on 26-Feb-2021 12:39:37
Advertisements