I have an html list
<select>
<option value="w" count="1">w (1)</option>
<option value="a" count="1">a (1)</option>
<option value="d" count="5">d (5)</option>
<option value="r" count="0">r (0)</option>
<option value="q" count="0">q (0)</option>
<option value="s" count="0">s (0)</option>
<option value="b" count="5">b (5)</option>
</select>
I want the list to be order by count first, then by value.
Output:
<select>
<option value="b" count="5">b (5)</option>
<option value="d" count="5">d (5)</option>
<option value="a" count="1">a (1)</option>
<option value="w" count="1">w (1)</option>
<option value="q" count="0">q (0)</option>
<option value="r" count="0">r (0)</option>
<option value="s" count="0">s (0)</option>
</select>
I know how to sort by count OR by value but I don’t find an easy way to combine them.
Sort by count:
select.sort(function (a, b) {
var c1 = parseInt($(a).attr('count'), 10);
var c2 = parseInt($(b).attr('count'), 10);
return c1 < c2 ? 1 : c1 > c2 ? -1 : 0;
});
and by value
select.sort(function (a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text());
});
I am thinking about building an object:
var map = {
5: ['d', 'b'],
1: ['a', 'w'],
0: ['r', 'q', 's']
};
Then sort each keys:
function keys(map) {
var keys = [];
for (var key in map) {
if (map.hasOwnProperty(key)) map[key].sort();
}
return keys;
}
keys(map);
map;
And finally reconstruct the select list.
Is there an easier way?
Try this:
With the comments removed, that’s just 6 lines of code.
There’s no need to wrap the second
returnin aelse, because the sort function won’t ever evaluate anelse, ifc1 === c2, since theifcontains areturnstatement.Now, the
sortfunction expectsX<0, X=0 or X>0to be returned (WhereXis the output), depending on ifais less than, equal to, or greater thanb. If you subtractbfroma, you get the values you need.