-4

i have a select option

<select>
<option>aaa</option>
<option>ccc</option>
<option>ddd</option>
<option>bbb</option>
</select>

How to sort them. so output will

aaa
bbb
ccc
ddd

this question is asked to me in an interview answer if any Know Thanks In advance

laaposto
  • 11,835
  • 15
  • 54
  • 71

3 Answers3

4

You can use use JavaScript sort method. It sorts the elements in lexical order. So you can set the innerHTML of the select element based on the result of the sort function.

Read more about the sort function here

Try:

$("select").html($('select option').sort(function (x, y) {

    return $(x).text() < $(y).text() ? -1 : 1;

}))

DEMO

laaposto
  • 11,835
  • 15
  • 54
  • 71
  • can u please explain it to me – mayank chaturvedi May 29 '14 at 12:28
  • In case anyone has options that look like "20 people", "5 people" and want to properly sort them (the "2" from "20" will come before "5") you can use `return parseInt($(x).text().split(' ')[0]) < parseInt($(y).text().split(' ')[0]) ? -1 : 1;` and "5 people" will come before "20 people". – nickpapoutsis Jul 09 '21 at 20:36
0

Add an id

<select id='myselect'>
<option>aaa</option>
<option>ccc</option>
<option>ddd</option>
<option>bbb</option>
</select>

Get all options in an array, sort it and then change the values of the select

var array = new Array();
$("#myselect option").each(function() { array.push($(this).text()) });
array.sort();

$("#myselect option").each(function(index,elem) { $(this).html(array[index]) });
Alexandru Chichinete
  • 1,166
  • 12
  • 23
0

Working Fiddle

$('#sort').click(function () {
$('select').each(function () {
   var options = $(this).children('option');
    options.sort(function (optionA, optionB) {
        return optionA.value.localeCompare(optionB.value);
    });
    $(this).empty().append(options);
});
});
Suhas Gosavi
  • 2,170
  • 19
  • 40