user7066345 user7066345 - 20 days ago 5
Javascript Question

jquery sorting function not working

The following sort function is not working for me:

function sortTags() {
var options = $('#ddlTags option').sort(tags_asc_sort);
$("#ddlTags").empty().append(options);
function tags_asc_sort(a, b) {
var aText = $(a).text().toUpperCase();
var bText = $(b).text().toUpperCase();
var compare = aText < bText ? -1 : 1;
}
}


I'm using a similar function for a different ddl that is working as expected. Any idea what the issue might be?

Answer

Based on the previous answers, and trying to be more purist, I would try to go with this sorter, which uses the LocaleCompare method.

function tags_asc_sort(a, b) {
    var aText = $(a).text().toUpperCase();
    var bText = $(b).text().toUpperCase();
    return aText.localeCompare(bText);
}

var text = 'hello this is test text hello'.split(' ');

    function tags_asc_sort(a, b) {
        var aText = a.toUpperCase();
        var bText = b.toUpperCase();
        return aText.localeCompare(bText);
    }

    console.log(text.sort(tags_asc_sort));