我有一個以物件為元素的陣列。我所做的是檢查titles 值是否包含某個字串,它確實會推送一個新陣列并記錄新陣列,并且該程序有效。
我想要的是當推送到新陣列時,我想優先找到首先推送的字串。
為了更好地解釋它,說我的陣列是這樣的:
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)
uj5u.com熱心網友回復:
為了達到您的要求,您可以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)
uj5u.com熱心網友回復:
你可以嘗試使用Array.reduce
邏輯:
- 回圈值并獲取字串的索引
- 使用索引作為鍵并將其插入物件中
- 最后,洗掉
"-",因為它們是不匹配的元素 - 此物件的值的回傳值
const myArr = [{"title": "test hello"}, {"title": "hello test"}, {"title": "test test"}]
const searchValue = 'Hello'
const matches = myArr.reduce((acc, item) => {
const index = item.title.toLowerCase().indexOf(searchValue.toLowerCase())
acc[index] = item
return acc
}, {})
delete matches["-1"];
console.log(Object.values(matches))
uj5u.com熱心網友回復:
您可以使用字串成員方法indexOf來獲取匹配模式的索引。然后過濾掉任何不匹配的元素。
const myArr = [
{
title: "test hello"
},
{
title: "hello test"
},
{
title: "test test"
}
];
const searchValue = "Hello";
const result = myArr
.map(({ title }) => {
var index = title
.toLocaleLowerCase()
.indexOf(searchValue.toLocaleLowerCase());
return {
match: index >= 0,
index: index,
title
};
})
.filter(({ match }) => match)
.sort((a, b) => a.index - b.index);
//expected output [{"title": "hello test"}, {"title": "test hello"}]
console.log(result);
在此類問題上,盡量不要過于頻繁地遍歷您的陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/507717.html
標籤:javascript
下一篇:按類名和樣式屬性JS按選擇器搜索
