The first thing you need to understand is that 12 really less than 9 if you are sorting text elements, not numbers. This is because <1> <2> less than <9> <nothing> , because 1 and 9 are the "primary keys" in this case.
The second problem you are facing is the length (9 1/2) - primary key or width (EE). I would suspect that the former will make more sense, so continue on that basis.
Having decided that the best option is to provide a sort function for the call, which turns each row into a numeric value, and then compares that value. For example:
- Get the first field with a separator (9) and set the value for it.
- If the next field exists and
1/2 , add 0.5 to this value. - If the last field exists (alpha unit), just convert it to some value less than
0.5 and add it (for example, a β 0.01, B β 0.02, ..., EEEE β 0.08, etc.).
The latter depends on the relative ordering of the width, I chose a typical American system.
As a result, you have a value that dictates the correct ordering, and your sort function can then simply perform a numerical comparison. The following is an example:
function xlat(s) { var s2 = s.split(" "); var n = parseInt(s2[0]); if (s2.length == 1) { return n; } var last = s2[1]; if (last == '1/2') { n = n + 0.5; if (s2.length == 2) { return n; } last = s2[2]; } var widths = ['A','B','C','D','E','EE','EEE','EEEE','F','G']; n = n + widths.indexOf(last) / 100; return n; } $("select").html($("option").sort(function (a, b) { var na = xlat(a.text); var nb = xlat(b.text); return na == nb ? 0 : na < nb ? -1 : 1; }));
The xlat functions are important xlat . It first splits the size into an array of 1, 2, or 3 elements and gets a numeric value for the first. If there is no second and third, this value is returned (processes bare sizes such as 9 or 13 ).
Otherwise, it decides whether the length of the half increment is - this is determined if the second field is 1/2 . At this point, it also determines if there is a width and returns the size.
Once this happened, we have the size (integer or half), and the last variable contains the width. Then we simply add a value based on this size position in the array, appropriately modified (divided by 100) so that it does not affect the main key.
Using this code with your own, you get (as expected):
9 D 9 EE 9 EEEE 9 1/2 D 9 1/2 EE 9 1/2 EEEE 10 EE 10 EEEE 10 1/2 EE 10 1/2 EEEE 11 EE 11 EEEE 11 1/2 EE 11 1/2 EEEE