我有一个对象数组
let array = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]
我正在尝试用以下逻辑来实现
array.filter((item) => {
return item.name.toLowerCase().includes(searchText);
});
我正在尝试基于“po”进行搜索,当我使用po进行搜索时,我能够以相同的顺序获取所有记录。
但是我需要按以下顺序获取结果以匹配第一个字符
电流输出:
[{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]
预期输出:
[{name: "poland"}, {name: "portugal"}, {name: "singpore"}, {name: "French Polynesia"}]
您可以使用
findIndex
,然后使用索引对值进行排序!
let array = [{
name: "singpore"
}, {
name: "French Polynesia"
}, {
name: "poland"
}, {
name: "portugal"
}]
const searchText = 'po';
console.log(array.filter((item) => {
return item.name.toLowerCase().includes(searchText);
}).sort((a, b) => {
const indexA= a.name.toLowerCase().indexOf(searchText);
const indexB= b.name.toLowerCase().indexOf(searchText);
return indexA - indexB;
}));