What is the most efficient way to sort an Html Select’s Options by value, while preserving the currently selected item?

Extract options into a temporary array, sort, then rebuild the list:

var my_options = $("#my_select option");
var selected = $("#my_select").val();

my_options.sort(function(a,b) {
    if (a.text > b.text) return 1;
    if (a.text < b.text) return -1;
    return 0
})

$("#my_select").empty().append( my_options );
$("#my_select").val(selected);

Mozilla’s sort documentation (specifically the compareFunction) and Wikipedia’s Sorting Algorithm page are relevant.

If you want to make the sort case insensitive, replace text with text.toLowerCase()

The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the unicode collation algorithm). Using localeCompare in the sort function is a good solution, eg:

my_options.sort(function(a,b) {
    return a.text.localeCompare(b.text);
});

Leave a Comment