javascript 从第一个数组开始,按数组的最后一个字母对数组重新排序,依此类推

6kkfgxo0  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(117)

因此,我尝试创建一个函数,从第一个数组开始,按最后一个字母对数组进行重新排序,依此类推
第一个数组TEAM最后一个字母M,则它将查找并匹配以字母M开头的数组,即MOIST,因此字母T将匹配TOKEN
示例:[“团队”、“令牌”、“潮湿”]到[“团队”、“潮湿”、“令牌”]
问题是我只得到[“团队”,“潮湿”]的结果

let array = ["team", "token", "moist"];
let newArr = [];

const reorderArr = () => {
// reorder array by their last letter starting with the first array and so on
console.log("ARRAY:", array);

array.forEach((arr, index) => {
   let currentWord = arr;
   console.log("LOOP: ", index);

if (!newArr.includes(currentWord)) {
  if (index === 0) {
    console.log("HIT ONCE");
    newArr.push(currentWord);
  } else {
    for (let x = 1; x < array.length; x++) {
      const nextWord = array[x];
      console.log("nextWord", nextWord);
      if (nextWord.slice(0, 1) === newArr[newArr.length - 1].slice(-1)) {
        console.log("HIT");
        newArr.push(nextWord);
      }
    }
  }
}
 });

console.log("REORDERED ARRAY:", newArr); // RESULT SHOULD BE ["team", "moist", "token"]
};

reorderArr();
z9smfwbn

z9smfwbn1#

您可以使用一个剩余单词数组和一个正确单词数组检查所有组合。

function reorder(array) {
    const
        check = (pool, result = []) => {
            if (!pool.length) return result;
            const last = result?.at(-1)?.at(-1);
            let longest = [];
            for (const word of pool) {
                if (last && last !== word[0]) continue;
                const temp = check(pool.filter(w => w !== word), [...result, word]);
                if (longest.length < temp.length) longest = temp;
            }
            return longest;
        };
    
    return check(array);
}

console.log(...reorder(["team", "token", "moist"]));

相关问题