检查数组是否按照JavaScript中某些加扰的字母顺序按字典顺序排序

我们需要编写一个JavaScript函数,该函数将字符串单词数组作为第一个参数。该函数的第二个参数将是一个字符串,其中包含所有26个英文小写字母,但以某种随机的乱序排列。

我们函数的任务是检查数组中的单词是否按照第二个自变量指定的顺序按字典顺序正确放置。如果是这样,我们应该返回true,否则返回false。

例如-

如果输入的单词数组和顺序为-

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

那么输出应该是-

const output = true;

因为在命令字符串中,“ t”位于“ i”之前,而“ i”位于“ m”之前。

示例

为此的代码将是-

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));
输出结果

控制台中的输出将是-

true