Issue
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"}]
Solution
You can achieve this by using the sort()
after filtering
let array = [
{ name: "singpore" },
{ name: "French Polynesia" },
{ name: "poland" },
{ name: "portugal" }
];
let searchText = "po";
let filteredArray = array
.filter((item) => item.name.toLowerCase().includes(searchText))
//compare the index of the search text in each name
.sort((a, b) => a.name.toLowerCase().indexOf(searchText) - b.name.toLowerCase().indexOf(searchText));
console.log(filteredArray);
Answered By - Mamun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.