3
$( 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

Harati
  • 47
  • 8

3 Answers3

4

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>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Use parseInt for a number sort:

arr.sort( (a, b) => parseInt(b, 10) - parseInt(a, 10) )
Peter Aron Zentai
  • 11,482
  • 5
  • 41
  • 71
1

You could use just the delta, which operands are casted to number by using the minus operator.

$(document).ready(function() {
    $('#myshp_search_field_7 option').sort(function(a, b) {
        return $(a).val() - $(b).val();
    }).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>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392