0

I have this script that I use to sort a list of li's, however it is not working when there is more than one digit, it is sorting with the first digit taking preference, so 10 comes before 2. Is there a way to modify this so it sorts it based on the numeric value?

jQuery.fn.sortDomElements = (function() {
    return function(comparator) {
        return Array.prototype.sort.call(this, comparator).each(function(i) {
              this.parentNode.appendChild(this);
        });
    };
})();

$("#sortable3, #sortable4").children().sortDomElements(function(a,b){
    akey = $(a).attr("sortkey");
    bkey = $(b).attr("sortkey");
    if (akey == bkey) return 0;
    if (akey < bkey) return -1;
    if (akey > bkey) return 1;
});
1
  • You need to convert the 'sortkey' attributes to integer, as they are being compared as strings right now. Commented Jan 18, 2015 at 5:10

2 Answers 2

2

You're comparing strings. When comparing strings you get this:

"10" <  "2"
true

Instead force the string to ints base 10:

parseInt("10", 10) <  parseInt("1", 10)
false

Trying this:

$("#sortable3, #sortable4").children().sortDomElements(function(a,b){
    akey = parseInt(($(a).attr("sortkey"), 10);
    bkey = parseInt($(b).attr("sortkey"), 10);
    if (akey == bkey) return 0;
    if (akey < bkey) return -1;
    if (akey > bkey) return 1;
});

should fix it.

Sign up to request clarification or add additional context in comments.

2 Comments

I would suggest always specifying the expected radix for parseInt()
Yes, you're right @jdphenix, that's an accepted best practice — edited my answer.
1

Try converting the key to a number.

akey = parseInt($(a).attr("sortkey");
...

1 Comment

I would suggest always specifying the expected radix for parseInt()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.