I'm working with an ecommerce platform that lacks the ability to reorder the options of our product attribute fields. It really sucks because to insert a new option you pretty much have to delete all of the existing ones and start over. I'm trying to do it client-side instead. Here's what I'm working with (this one's for a shoe size):
- 9 EE
- 9 1/2 EE
- 10 EE
- 10 1/2 EE
- 11 EE
- 11 1/2 EE
- 9 EEEE
- 9 1/2 D
- 9 1/2 EEEE
- 10 EEEE
- 10 1/2 EEEE
- 11 EEEE
- 9 D
- 11 1/2 EEEE
These are actually the text of some <option>
s in a form. The format of the values is X Y Z
where:
X
is a whole numberY
is the string "1/2" and may not be presentZ
is a letter code which is either "D", "E", "EEE", or "EEEE", and may not be present
The desired order of the above would be this:
- 9 D
- 9 1/2 D
- 9 EE
- 9 1/2 EE
- 9 EEEE
- 9 1/2 EEEE
- 10 EE
- 10 1/2 EE
- 10 EEEE
- 10 1/2 EEEE
- 11 EE
- 11 1/2 EE
- 11 EEEE
- 11 1/2 EEEE
I've learned a little bit about javascript's sort()
function but haven't been able to fully comprehend how the comparison function that you can pass to it works. I've got this so far:
<select>
<option>9 EE</option>
<option>9 1/2 EE</option>
<option>10 EE</option>
<option>10 1/2 EE</option>
<option>11 EE</option>
<option>11 1/2 EE</option>
<option>9 EEEE</option>
<option>9 1/2 D</option>
<option>9 1/2 EEEE</option>
<option>10 EEEE</option>
<option>10 1/2 EEEE</option>
<option>11 EEEE</option>
<option>9 D</option>
<option>11 1/2 EEEE</option>
</select>
I started with the code taken from this answer: https://stackoverflow.com/a/667198/398242
$("select").html($("option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
Which sorts the items like this (doesn't work for even the first criteria):
- 10 1/2 EE
- 10 1/2 EEEE
- 10 EE
- 10 EEEE
- 11 1/2 EE
- 11 1/2 EEEE
- 11 EE
- 11 EEEE
- 9 1/2 D
- 9 1/2 EE
- 9 1/2 EEEE
- 9 D
- 9 EE
- 9 EEEE
I see that in javascript '11' > '9'
returns false
, which in no way makes sense to me.
MDN describes the compare function argument as such, and I kind of get it:
function compare(a, b) {
if (a is less than b by some ordering criterion)
return -1;
if (a is greater than b by the ordering criterion)
return 1;
// a must be equal to b
return 0;
}
...but I haven't got a clue how to adapt this to fit my requirements. I've tried a few things but I just feel like I'm shooting in the dark. I've tried to show that I've taken some time to attempt an understanding of this problem. I'm interested in learning more, but for now I'd just like to get this issue solved.
http://jsfiddle.net/DnwJ6/ Any clues?