You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中按匹配优先级正确排序过滤后的国家列表?

解决国家列表筛选排序问题

你的问题核心是过滤后没有按设定的优先级排序——当前只是简单筛选出包含检索词的项,但没区分「以检索词开头」和「包含检索词但位置靠后」的优先级,也没按检索词出现位置排序。咱们直接修改filtered计算属性就能搞定:

@computed get filtered() {
  const term = this.filterTermValue;
  // 先过滤出包含检索词的国家(大小写不敏感)
  const filteredList = this.countriesList.filter(country => 
    country.name.toLowerCase().includes(term)
  );

  // 按规则排序:
  return filteredList.sort((a, b) => {
    const aNameLower = a.name.toLowerCase();
    const bNameLower = b.name.toLowerCase();
    
    // 第一优先级:是否以检索词开头
    const aStartsWith = aNameLower.startsWith(term);
    const bStartsWith = bNameLower.startsWith(term);
    
    if (aStartsWith && !bStartsWith) return -1; // a排前面
    if (!aStartsWith && bStartsWith) return 1;  // b排前面
    
    // 第二优先级:检索词在名称中的出现位置,位置越靠前排越前
    const aIndex = aNameLower.indexOf(term);
    const bIndex = bNameLower.indexOf(term);
    return aIndex - bIndex;
  });
}

代码逻辑说明:

  1. 过滤阶段:用includes替代indexOf > -1,语义更清晰,效果完全一致(都是检查名称是否包含检索词)。
  2. 排序阶段:
    • 先判断两个国家名称是否以检索词开头,开头的项直接排在更前面;
    • 如果都开头或都不开头,就比较检索词在名称中的起始索引,索引值越小(出现越早)的项排越前。

验证你的例子:

  • 输入unit时:
    • United States转小写后是united states,以unit开头,直接排第一;
    • The United Kingdom转小写后the united kingdom中unit的索引是4,Emirates, The United Arab中unit的索引是12,所以前者排第二,后者第三,完全符合预期。
  • 输入in时:
    • India转小写india以in开头,排第一;
    • China转小写china中in的索引是2,The United Kingdom中in的索引是10,所以China排第二,后者第三,和你想要的结果完全匹配。

另外,你的onChangeFilterTerm已经把输入转成小写了,所以排序时直接用term就行,省了重复转义的步骤~

内容的提问来源于stack exchange,提问作者Wonka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:58:36