I have an array of objects
let array = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]
I am trying to implement with below logic
array.filter((item) => {
return item.name.toLowerCase().includes(searchText);
});
I am trying to search based on "po", when i search with po i am able to get all the records in the same order.
But i need to get the results in the below order to match the first characters
Current output:
[{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]
Expected output:
[{name: "poland"}, {name: "portugal"}, {name: "singpore"}, {name: "French Polynesia"}]
2
Answers
You can use
indexOf
then sort the values using the indexes!You can achieve this by using the
sort()
after filtering