Reputation: 42185
I have a JSON array of potential results for an autocomplete list.
The list is defined as:
var fundList = [ //there's lots more than this
{ "name": "Pension Managed Fund 1" },
{ "name": "Managed Property Fund 2" },
{ "name": "Retirement Managed Fund 3" },
{ "name": "Retirement Managed Fund 4" }
]
I need to sort the list alphabetically, but it has to also be ordered by the relevance to the value entered into textbox (which triggers the automcomplete)
So for example, if the user types "Managed" into the textbox, the list above would be sorted as follows:
Managed Property Fund 2
Pension Managed Fund 1
Retirement Managed Fund 3
Retirement Managed Fund 4
If they typed "Retirement", the list would be sorted:
Retirement Managed Fund 3
Retirement Managed Fund 4
Managed Property Fund 2
Pension Managed Fund 1
If "Fund" was typed, the order would be normal alphabetical order:
Managed Property Fund 2
Pension Managed Fund 1
Retirement Managed Fund 3
Retirement Managed Fund 4
Is there any in-built functionality in JavaScript or jQuery which will do this?
Upvotes: 4
Views: 4051
Reputation: 6928
Array.prototype.sort can take a function as a comparator; I guess you need to sort every string containing a search term ahead of every string without it, and break ties alphabetically:
var query = 'Managed';
fundList.sort(function(a, b)
{
var match_a = a.name.indexOf(query) >= 0;
var match_b = b.name.indexOf(query) >= 0;
if(match_a && !match_b)
return -1;
if(!match_a && match_b)
return 1;
if(a.name < b.name)
return -1;
if(a.name > b.name)
return 1;
return 0;
});
Use this as a starting point; instead of String.prototype.indexOf to work out if a string matches the query I'd at the very least ignore case and spacing.
Upvotes: 1
Reputation: 3885
javascript has an array sort method that can take a function as a parameter this will allow you to define how you want things sorted
for example
var fundList = [ //there's lots more than this
{ "name": "Pension Managed Fund 1" },
{ "name": "Managed Property Fund 2" },
{ "name": "Retirement Managed Fund 3" },
{ "name": "Retirement Managed Fund 4" }
]
funcList.sort(function(a, b){
if (a == b)
{
return 0;
}
if (SOME CRITERIA TO SORT a AT A LOWER INDEX THEN b)
{
return -1;
}
if (SOME CRITERIA TO SORT b AT A LOWER INDEX THEN a)
{
return 1;
}
});
Upvotes: 1