我有一个以对象作为元素的数组。我所做的是检查标题值是否包含某个字符串,并且它确实推送了一个新数组并记录了新数组,并且该过程有效。
我想要的是,当推送到新数组时,我想优先考虑最先找到的字符串。
为了更好地解释它,我的数组是这样的:
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/