Sort the values in the jQuery Autocomplete

var myarray= ["JOAQUIN", "BERNARDINO", "MODOC","ALASKA","MADERA", "ANDERSON"]
myarray.sort();

Read More

See Demo

we are passing two arguments into source one is request and second is response,

  • request is stands for request object we are making, in our case it is the letter we are typing into textbox.

  • response is function which will return us auto complete selection options.

now inside $.map we are checking typed words with array we have named json.

json.toUpperCase().indexOf(request.term.toUpperCase()) this line convert typed word and array to same case and return it.

and matches would be the final result which has list of item that you have asked.

and response(matches); will send it to autocomplete.


I faced the same issue with objects rather than simple string array, and sorting needs to be done after retrieving the results (to achieve "startswith" suggestions at the top of the list). so for future searchers, i'll add my solution.

using JQuery you can search for strings within your results object's .label that start with the user input, and merge the rest of the result to those, after merging use Underscore.js library to remove duplicates.

for example:

var objects_array = [{"label":"A_ABC","value":"0"},{"label":"B_ABC","value":"1"},{"label":"C_ABC","value":"2"}];

$(document).ready ( function() {

$('#search').autocomplete({
    source: function (request, response) {

        var results = $.ui.autocomplete.filter(objects_array, request.term);               

        var top_suggestions = $.grep(results, function (n,i) {
                                 return (n.label.substr(0, request.term.length).toLowerCase() == request.term.toLowerCase());
                              });

        var merged_results = $.merge(top_suggestions,results);

        var final_results = _.uniq(merged_results,"label");

        response(final_results);
    }
});

});

jquery ui starts with

result example: http://i.stack.imgur.com/GKJ8d.png