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

JavaScript中基于startsWith对搜索过滤后的数组进行排序的方法

实现方案

你可以对过滤后的数组添加自定义排序逻辑,优先将以搜索词开头的匹配项排在最前面,实现代码如下:

// 提前将搜索词转小写存储,避免重复转换提升性能
const searchLower = search.toLocaleLowerCase();
const filtered = list.filter((m) =>
  m.toLowerCase().includes(searchLower)
);
// 对过滤结果做自定义排序
const sortedResult = filtered.sort((a, b) => {
  const aLower = a.toLowerCase();
  const bLower = b.toLowerCase();
  // 匹配优先级判断:startsWith匹配优先级高于普通包含匹配
  const aIsStartMatch = aLower.startsWith(searchLower);
  const bIsStartMatch = bLower.startsWith(searchLower);
  if (aIsStartMatch && !bIsStartMatch) return -1;
  if (!aIsStartMatch && bIsStartMatch) return 1;
  // 两者匹配优先级相同时,按字典序默认排序即可
  return aLower.localeCompare(bLower);
});

效果验证

以你给出的示例数组[brother, brothersmad, other]为例,当搜索输入为other时,只有other项满足startsWith匹配条件,会直接排在结果的第一位,符合需求。

如果需要补充更精细的排序规则,比如同为startsWith匹配的项中更短的字符串优先,可以在排序逻辑中增加长度判断:

if (aIsStartMatch && bIsStartMatch) {
  return a.length - b.length;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 04:12:11