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());
}
});
}
}