0

I'm going to sort elements on my page by their names. This is my code: http://jsfiddle.net/q3a9gmm6/1/

  • I used charCodeAt() to be able to sort elements with UTF-8 values like Persian.

Sometimes I get wrong answers. As you can see in the fiddle "Windows Phone" must be after "Windows Mobile" and "AMD" on top.

And I think that the code should be optimized to reduced the complexity.

What is the problem?

JQuery:

var itms_ind = 8;   

for (i = 0; i <= itms_ind; i++) {
    var first = $('.container div label:eq(0)');
    var first_char1_int = first.text().substr(0, 1).toLowerCase().charCodeAt();
    var first_char2_int = 
        first.text().substr(first.text().indexOf(' ') + 1, 1).toLowerCase().charCodeAt();

    for (j = 0; j <= itms_ind; j++)
        {
            $('.container div label').each(function() {
                var current = $(this);
                var current_char1_int = current.text().substr(0, 1).toLowerCase().charCodeAt();
                var current_char2_int = current.text().
                    substr(current.text().indexOf(' ') + 1, 1).toLowerCase().charCodeAt();

                if ((current_char1_int < first_char1_int)){
                    first.parent().before(current.parent());    
                } else
                if ((first_char1_int == current_char1_int)){
                    if (first_char2_int < current_char2_int)
                        current.parent().after(first.parent());
                }
            });
        }
}
VafaK
  • 514
  • 1
  • 6
  • 22

2 Answers2

4

Try a basic sorting like

var els = $('.container div').get();

els.sort(function(el1, el2){
    return $(el1).text().trim().localeCompare($(el2).text().trim())
})

$('.container').append(els)

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Check this fiddle

I totally change your solution for sorting.

var items = [];
$('.container div label').each(function(){
    $this = $(this);
    items.push($this.text());

});
items.sort();
Saman Gholami
  • 3,416
  • 7
  • 30
  • 71