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

如何按字符串匹配位置优先级排序包含指定字符串的数组元素?

解决方案

你可以在筛选完成后,对结果数组按搜索字符串在title中的出现位置进行排序,核心是利用indexOf获取匹配位置,再根据位置值从小到大排序。

修改后的代码如下:

const myArr = [{
  "title": "test hello"
}, {
  "title": "hello test"
}, {
  "title": "test test"
}]

const searchValue = 'Hello'
const lowerSearch = searchValue.toLowerCase() // 统一转小写,避免大小写影响

let foundArr = []

for (var i = 0; i < myArr.length; i++) {
  const lowerTitle = myArr[i].title.toLowerCase()
  if (lowerTitle.includes(lowerSearch)) {
    foundArr.push(myArr[i])
  }
}

// 按搜索词出现位置排序,位置越靠前排越前
foundArr.sort((a, b) => {
  const posA = a.title.toLowerCase().indexOf(lowerSearch)
  const posB = b.title.toLowerCase().indexOf(lowerSearch)
  return posA - posB
})

console.log(foundArr)
// 输出:[{"title": "hello test"}, {"title": "test hello"}]

关键逻辑说明

  • 先把搜索词转成小写并缓存,避免重复转换,提升效率
  • 排序时,对每个元素的title转小写后,用indexOf获取搜索词的起始索引位置
  • sort方法中,返回两个元素的位置差值:如果posA小于posB,则a会排在b前面,实现位置靠前的元素优先

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:10:17