[英]prioritize pushing element to array
我有一個以對象為元素的數組。 我所做的是檢查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)
為了達到您的要求,您可以通過值中匹配字符串的索引對數組進行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)
您可以嘗試使用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))
您可以使用字符串成員方法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);
在此類問題上,盡量不要過於頻繁地迭代您的 arrays。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.