Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort on two digits instead of one? [duplicate]

$( document ).ready(function() {
    var options = $('select#myshp_search_field_7 option');
    var arr = options.map(function(_, o) {
        return {
            t: $(o).text(),
            v: o.value
        };
    }).get();
    arr.sort(function(o1, o2) {
        return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
    });
    options.each(function(i, o) {
        console.log(i);
        o.value = arr[i].v;
        $(o).text(arr[i].t);
    });
});

So this sorts my select field but it only sorts on the first digit(number)>

<select id='myshp_search_field_7'>
    <option value='10'>10</option>
    <option value='5'>5</option>
    <option value='3'>3 </option>
    <option value='11'>11 </option>
</select>

The result of the code is : 10 , 11 , 3, 5

But i want it to be : 3, 5 , 10, 11

like image 274
Harati Avatar asked Jan 23 '26 22:01

Harati


1 Answers

The issue is because you are comparing string values. To correct this coerce the values in the sort() logic to integers using parseInt():

arr.sort(function(o1, o2) {
  var o1t = parseInt(o1.t, 10), o2t = parseInt(o2.t, 10);
  return o1t > o2t ? 1 : o1t < o2t ? -1 : 0;
});

Also note that you can simplify the sort logic as you can work directly on the option elements themselves without having to first map() an array of objects from them. Try this:

$(document).ready(function() {
  $('#myshp_search_field_7 option').sort(function(a, b) {
    var aVal = parseInt($(a).val(), 10), bVal = parseInt($(b).val(), 10);
    return aVal > bVal ? 1 : aVal < bVal ? -1 : 0;
  }).appendTo('#myshp_search_field_7');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myshp_search_field_7">
    <option value="10">10</option>
    <option value="5">5</option>
    <option value="3">3</option>
    <option value="11">11</option>
</select>
like image 109
Rory McCrossan Avatar answered Jan 26 '26 14:01

Rory McCrossan