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

如何根据用户输入过滤对象数组并按前缀匹配排序结果

实现前缀优先的过滤排序

你可以在过滤后对结果数组进行排序,通过判断项是否以搜索文本开头来调整优先级,让前缀匹配的项排在最前面。

完整代码实现

let array = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}];
const searchText = "po".toLowerCase();

// 1. 过滤出所有包含搜索文本的项
const filteredItems = array.filter(item => 
  item.name.toLowerCase().includes(searchText)
);

// 2. 排序:前缀匹配项优先,其余保持原数组相对顺序
const sortedItems = filteredItems.sort((a, b) => {
  const aLower = a.name.toLowerCase();
  const bLower = b.name.toLowerCase();
  const aIsPrefix = aLower.startsWith(searchText);
  const bIsPrefix = bLower.startsWith(searchText);

  // 前缀匹配项排前面
  if (aIsPrefix && !bIsPrefix) return -1;
  if (!aIsPrefix && bIsPrefix) return 1;
  // 同类型项保持原顺序(ES2019+ sort是稳定排序)
  return 0;
});

console.log(sortedItems);

兼容旧环境的稳定排序方案

如果你的运行环境不支持ES2019的稳定排序,可以通过记录原始索引来保证同类型项的原顺序:

let array = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}];
const searchText = "po".toLowerCase();

// 给每个项添加原始索引
const indexedArray = array.map((item, idx) => ({ ...item, _idx: idx }));

const filteredItems = indexedArray.filter(item => 
  item.name.toLowerCase().includes(searchText)
);

const sortedItems = filteredItems.sort((a, b) => {
  const aLower = a.name.toLowerCase();
  const bLower = b.name.toLowerCase();
  const aIsPrefix = aLower.startsWith(searchText);
  const bIsPrefix = bLower.startsWith(searchText);

  if (aIsPrefix && !bIsPrefix) return -1;
  if (!aIsPrefix && bIsPrefix) return 1;
  // 同类型项按原始索引排序
  return a._idx - b._idx;
}).map(({ _idx, ...rest }) => rest); // 移除临时索引

console.log(sortedItems);

输出结果

两种方案都会得到你期望的排序:

[{name: "poland"}, {name: "portugal"}, {name: "singpore"}, {name: "French Polynesia"}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:41:02