Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple sorting by number script, 3 lines, doesn't sort last few li's correctly, why?

http://jsfiddle.net/nicktheandroid/6BAfH/1/

The list-elements are sorted accordingly by the number in their span. Why is it that the last few numbers are out of order? I'm confused.

Jquery

function sortEm(a,b){
  return parseInt($('span', a).text()) < parseInt($('span', b).text()) ? 1 : -1;
}

$('li').sort(sortEm).prependTo($('ul#test'));

HTML

<ul id="test">

    <li> Cups
        <span>12</span>
    </li>

    <li> Plates
        <span>18</span>
    </li>

    <li> Forks
        <span>03</span>
    </li>

    <li> Knives
        <span>08</span>
    </li>

    <li> Bowls
        <span>55</span>
    </li>
</ul>
like image 502
android.nick Avatar asked Jan 08 '12 13:01

android.nick


1 Answers

Welcome to the world of octal numbers.

If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

Use the radix to base 10 with parseInt.

parseInt($('span', a).text(), 10)
like image 191
epascarello Avatar answered Oct 02 '22 09:10

epascarello