在 JavaScript 中按字典顺序返回已排序的数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 15:08:17

我们需要编写一个 JavaScript 函数,该函数接受两个数组,即 arr1 和 arr2。我们的函数应按字典顺序返回 arr1 字符串的已排序数组,这些字符串是 arr2 字符串的子字符串。

示例

其代码为 −

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));

输出

控制台中的输出将是 −

[ 'live', 'strong' ]

相关文章


有用资源