Toniq
Toniq

Reputation: 5006

Alphabetical string sort

I am looking for an algorithm that will sort option values alphabetically.

$(this).html($("option", $(this)).sort(function(a, b) { 
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 
}));

With this above code it appears that its working, however as soon as I introduce multiple works, sorting becomes unpredictable.

Let say or example I am trying to sort this:

<select class='whatever'>
    <option value='Lorem dva'>Lorem dva</option>
    <option value='a1'>a1</option>
    <option value='pl1'>pl1</option>
</select>

I am using jQuery.

Thank you!

Upvotes: 1

Views: 104

Answers (1)

Sergii Dymchenko
Sergii Dymchenko

Reputation: 7209

Your example is already sorted, because capital 'L' goes before 'a' in ASCII. Maybe you want to add toLowerCase()?

And you should re-insert sorted options into the DOM:

$(document).ready(function () {
    $(this).html($("option", $(this)).sort(function (a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }).appendTo(".whatever"));
});

http://jsfiddle.net/5zpTu/3/

Upvotes: 2

Related Questions