Reputation: 105
I have an array and i want to sorted it. However; I have an empty dropdown menu and i want to populated. Im stuck. How can populate my dropdown menu with the sorted array.
enter code here
<select id="dropdownList">
<option></option>
</select>
enter code here
var array = ["vintage","frames","treats","engraved", "stickers", "jewelerybox", "flask"];
array.sort(function(val1 , val2){
return val1.localeCompare(val2);
});
console.log(array); // ["engraved", "flask", "frames", "jewelerybox", "stickers", "treats",
Upvotes: 1
Views: 154
Reputation: 5953
You can do it with for loop
,by writing it to innerHTML
of the select
var array = ["vintage", "frames", "treats", "engraved", "stickers", "jewelerybox", "flask"];
array.sort(function(val1, val2) {
return val1.localeCompare(val2);
});
var select = document.getElementById("dropdownList");
for (var i = 0; i < array.length; i++) {
select.innerHTML += '<option>' + array[i] + '</option>';
}
<select id="dropdownList">
</select>
Upvotes: 3