I have to implement a search functionality in an app I am currently working on. However, the problem is how we display the results. For Example,
const queries = ['revised sales report','sales report', 'revision: sales investors report']
function filterResults(term) {
const search = queries.filter(item =>item.toLowerCase().includes(term.toLowerCase()));
return search;
}
console.log(filterResults('sales report'))
The above function gives me
[
"revised sales report",
"sales report"
]
as results. But however, the desired output should be,
[
"sales report",
"revised sales report",
"revision: sales investors report"
]
That is, my first result should always start with the exact search string i.e, even though sales report is the second item in the array, that is the exact match so it should appear first, second result can contain string at any place, i.e, the first item in the array has the search term but it starts with some other word and hence it should appear second. and subsequent result can have each input in different places of the sentence , i.e, the third item in the array has both the term sales and report but it is in disconnected and appears in different part of the sentence so it should appear after the second result. But the function I made above completely ignores the third result.
I have no clue how to approach this. I just started working 3 months ago. Any pointers on how to approach would be helpful.
[]. Post a better example that makes sense so we can understand what is wrong.filterResults()function returns an array of objects shaped as{ result: 'foo', priority: 1 }, where you set the priority according to your need (1 ifterm === item, 2 ifitem.indexOf(term) > -1, 3 if item contains any of the words in term - here you will have to split term and loop through the resulting array). Then you can simply sort the results by theirpriority