I have some data in the database used for a SEARCH BAR.
In this table the field is called searchPeople (all lowercase) and contains data like:
Name##CityName
john##rome
romeu##napoli
romeu2##milan
So the user types on the SEARCH BAR some thing Rome, people that contain Rome in either their name or city. The search works well but I would like to "PRIORITIZE" the exact match String on top of the array. currently the data comes in random by the database order
{
name: 'John',
city: 'Rome'
}
Should be on top because the city matches === the string given by the user. THis can either be the name or city, I just gave an example using city match
const people = [{
name: 'Romeu',
city: 'Napoli'
},
{
name: 'John',
city: 'Rome' // this object should be first because there is a matching result
},
{
name: 'Romeu2',
city: 'Milan'
}
];
console.log(people);
// How can I sort people array with most relevant results on top?
Is there a way to sort my array to put the more correct search results on top?
.sortpart of your codesortsortcan accept a function that accepts two elements from your array. This comparator then returns the relationship between the elements (a equals b, a < b, a > b). You only need to implement this comparator according to your requirements.