按某个单词对列表进行排序

我需要按特定单词对数组列表进行排序。任何帮助,将不胜感激。谢谢你。

 List=[microphone,phone,telephone,mobilephone]
    
 word="pho"

答案应该是,

答案= [ PHO NE,远程PHO NE,微PHO NE,移动PHO NE]

回答

您可以使用indexOf()获取索引号并将其传递给sort方法。

const list = ["microphone", "phone", "telephone", "mobilephone"];

const sortBySubstring = (words, match) => {
  return words.sort((a, b) => {
    return a.indexOf(match) - b.indexOf(match);
  });
}

const result = sortBySubstring(list, "pho");

console.log(result);

编辑:

如果您的列表中有一个不包含子字符串的单词,它将被放置在数组的开头。有一些方法可以改变这种行为。

首先,您可以使用includes()检查它是否存在,如果不存在则将其放在数组的末尾

const list = ["microphone", "phone", "telephone", "mobilephone", "telemobile"];

const sortBySubstring = (words, match) => {
  return words.sort((a, b) => {
    if(!a.includes(match) || !b.includes(match)) return 1;
    
    return a.indexOf(match) - b.indexOf(match);
  });
}

const result = sortBySubstring(list, "pho");

console.log(result);

另一种选择是filter()掉不包含给定子字符串的单词

const list = ["microphone", "phone", "telephone", "mobilephone", "telemobile"];

const sortBySubstring = (words, match) => {
  const contains = words.filter((word) => word.includes(match));

  return contains.sort((a, b) => {
    return a.indexOf(match) - b.indexOf(match);
  });
}

const result = sortBySubstring(list, "pho");

console.log(result);


以上是按某个单词对列表进行排序的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>