javascript - 优先将元素插入数组

标签 javascript

我有一个以对象作为元素的数组。我所做的是检查标题值是否包含某个字符串,并且它确实推送了一个新数组并记录了新数组,并且该过程有效。

我想要的是,当推送到新数组时,我想优先考虑最先找到的字符串。

为了更好地解释它,我的数组是这样的:

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

如果我的搜索字符串是 hello 我希望我的新数组是这样的:

[{"title": "hello test"}, {"title": "test hello"}]

最先找到的搜索字符串将放在最前面。我怎样才能实现这个目标?提前致谢。

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

const searchValue = 'Hello'

let foundArr = []

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

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

最佳答案

要实现您的要求,您可以通过值中匹配字符串的索引对数组进行sort()

此外,您还可以使用 filter() 来查找匹配项而不是显式 for 循环,从而简化逻辑:

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

const searchValue = 'Hello'.toLowerCase();
let foundArr = myArr
  .filter(o => o.title.toLowerCase().includes(searchValue))
  .sort((a, b) => a.title.toLowerCase().indexOf(searchValue) > b.title.toLowerCase().indexOf(searchValue) ? 1 : -1);

console.log(foundArr)

关于javascript - 优先将元素插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73715617/

相关文章:

javascript - 解决 Angular 应用程序中的 Moment.js 弃用警告

javascript - 如何转换这个路由器路由?

javascript - Angular 6 + Bootstrap 4 全选和取消全选复选框

javascript - fancybox 关闭后删除加载的元素

javascript - React onMouseEnter/onMouseLeave 没有按预期工作(奇怪的行为)

javascript - Angular 更新表单填充输入字段,但仍然在控制台中返回错误?

javascript - 为什么不绘制以编程方式插入的 SVG <tspan> 元素,d3.js 除外?

javascript - Jquery 脚本不引起任何交互

javascript - 当所有项目都已在 Ruby on Rails 中呈现时,隐藏“加载更多”按钮

javascript - 使用 React 生成动态 PDF