0

I want to change all the options of a select element when user clicks on the button. However, the new data appended inside the select tags don't follow their orders in the newOptions variable. It puts all the values with keys leading with 0 to the bottom of the list although they are declared and should be on the top. How can I fix this issue?

Expected:

<select name="car" id="car">
    <option value="0">00</option>
    <option value="5">05</option>
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="45">45</option>
</select>

Got

<select name="car" id="car">
    <option value="15">15</option>
    <option value="30">30</option>
    <option value="45">45</option>
     <option value="0">00</option>
    <option value="5">05</option>
</select>

function change() {
  $("#car").empty();

  newOptions = {
    "00": 0,
    "05": 5,
    "15": 15,
    "30": 30,
    "45": 45
  }

  for (const [k, v] of Object.entries(newOptions)) {
    $("#car").append($("<option></option>").attr("value", v).text(k));
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="car" id="car">
  <option value="00">Toyota</option>
  <option value="10">BMW</option>
  <option value="20">Honda</option>
</select>

<input type="submit" onclick="change()" value="Change select options">
Louis Tran
  • 1,078
  • 16
  • 37
  • 1
    This is a perfect example why *objects should not be used in situations where order is important*. Objects will always have their integer keys (`15`, `30`, and `45`) sorted first. [Further reading.](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) Consider a `Map` or `Array` instead. – Tyler Roper Mar 03 '20 at 20:50
  • https://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery – Ctznkane525 Mar 03 '20 at 20:52

1 Answers1

0

Apply sort function after the Object.entries.

function change() {
  $("#car").empty();

  newOptions = {
    "00": 0,
    "05": 5,
    "15": 15,
    "30": 30,
    "45": 45
  }

  for (const [k, v] of Object.entries(newOptions).sort(function(a, b) {return a - b;})) {
   $("#car").append($("<option></option>").attr("value",v).text(k));
}
} 
Nathan Bruet
  • 266
  • 1
  • 3
  • 14