<p>I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's <code>text</code>, <code>value</code>, and <code>selected</code> properties, but I don't think that javascript's built in <code>Array.sort()</code> would work correctly.</p>

[{'answer_id': 45890, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 3, 'selected': False, 'text': "<p>Well, in IE6 it seems to sort on the nested array's [0] item:</p>\n\n<pre><code>function sortSelect(selectToSort) {\n    var arrOptions = [];\n\n    for (var i = 0; i &lt; selectToSort.options.length; i++)  {\n        arrOptions[i] = [];\n        arrOptions[i][0] = selectToSort.options[i].value;\n        arrOptions[i][1] = selectToSort.options[i].text;\n        arrOptions[i][2] = selectToSort.options[i].selected;\n    }\n\n    arrOptions.sort();\n\n    for (var i = 0; i &lt; selectToSort.options.length; i++)  {\n        selectToSort.options[i].value = arrOptions[i][0];\n        selectToSort.options[i].text = arrOptions[i][1];\n        selectToSort.options[i].selected = arrOptions[i][2];\n    }\n}\n</code></pre>\n\n<p>I'll see if this works in other browsers...</p>\n\n<p>Edit: it works in Firefox too, woo hoo!</p>\n\n<p>Is there an easier way than this though? is there some method built into javascript or jQuery that sorts selects that I am missing, or is this the best way?</p>\n"}, {'answer_id': 45971, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 2, 'selected': False, 'text': '<p><code>Array.sort()</code> defaults to converting each element to a string, and comparing those values. So <code>["value", "text", "selected"]</code> gets sorted as <code>"value, text, selected"</code>. Which will probably work fine, most of the time. </p>\n\n<p>If you do want to sort on value alone, or interpret value as a number, then you can pass a comparison function into sort():</p>\n\n<pre><code>arrOptions.sort(function(a,b) { return new Number(a[0]) - new Number(b[0]); });\n</code></pre>\n'}, {'answer_id': 45974, 'author': 'bdukes', 'author_id': 2688, 'author_profile': 'https://Stackoverflow.com/users/2688', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s <a href="http://dev.jquery.com/ticket/255" rel="noreferrer">a closed jQuery ticket</a> for a sort that should work, but just wasn\'t included in the core.</p>\n\n<pre><code>jQuery.fn.sort = function() {\n  return this.pushStack( [].sort.apply( this, arguments ), []);\n};\n</code></pre>\n\n<p>Referenced from <a href="http://groups.google.com/group/jquery-en/browse_thread/thread/e0d6c199552dd1f7/2f05ad6d400dd962?lnk=gst&amp;q=array+sorting" rel="noreferrer">a Google Groups thread</a>, I think you just pass in a function that is used to sort, like so</p>\n\n<pre><code>function sortSelect(selectToSort) {\n    jQuery(selectToSort.options).sort(function(a,b){ \n        return a.value &gt; b.value ? 1 : -1; \n    });\n}\n</code></pre>\n\n<p>Hope it helps!</p>\n'}, {'answer_id': 1885355, 'author': 'Mark', 'author_id': 3915, 'author_profile': 'https://Stackoverflow.com/users/3915', 'pm_score': 8, 'selected': True, 'text': '<p>Extract options into a temporary array, sort, then rebuild the list:</p>\n\n<pre><code>var my_options = $("#my_select option");\nvar selected = $("#my_select").val();\n\nmy_options.sort(function(a,b) {\n    if (a.text &gt; b.text) return 1;\n    if (a.text &lt; b.text) return -1;\n    return 0\n})\n\n$("#my_select").empty().append( my_options );\n$("#my_select").val(selected);\n</code></pre>\n\n<p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort" rel="noreferrer" title="Mozilla&#39;s sort documentation">Mozilla\'s sort documentation</a> (specifically the compareFunction) and <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="noreferrer">Wikipedia\'s Sorting Algorithm page</a> are relevant.</p>\n\n<p>If you want to make the sort case insensitive, replace <code>text</code> with <code>text.toLowerCase()</code></p>\n\n<p>The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the <a href="http://www.unicode.org/reports/tr10/" rel="noreferrer">unicode collation algorithm</a>). Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare" rel="noreferrer">localeCompare</a> in the sort function is a good solution, eg:</p>\n\n<pre><code>my_options.sort(function(a,b) {\n    return a.text.localeCompare(b.text);\n});\n</code></pre>\n'}, {'answer_id': 4745818, 'author': 'Tom Maeckelberghe', 'author_id': 1421542, 'author_profile': 'https://Stackoverflow.com/users/1421542', 'pm_score': 4, 'selected': False, 'text': '<p>I\'ve just wrapped Mark\'s idea in a jquery function</p>\n\n<pre><code>$(\'#your_select_box\').sort_select_box();\n</code></pre>\n\n<p>JQuery function:    </p>\n\n<pre><code>$.fn.sort_select_box = function(){\n    var my_options = $("#" + this.attr(\'id\') + \' option\');\n    my_options.sort(function(a,b) {\n        if (a.text &gt; b.text) return 1;\n        else if (a.text &lt; b.text) return -1;\n        else return 0\n    })\n   return my_options;\n}\n</code></pre>\n'}, {'answer_id': 5432746, 'author': 'JaredC', 'author_id': 339532, 'author_profile': 'https://Stackoverflow.com/users/339532', 'pm_score': 4, 'selected': False, 'text': '<p>Modified Tom\'s answer above slightly so that it actually modifies the contents of the select box to be sorted, rather than just returning the sorted elements.</p>\n\n<pre><code>$(\'#your_select_box\').sort_select_box();\n</code></pre>\n\n<p>jQuery function:</p>\n\n<pre><code>$.fn.sort_select_box = function(){\n    // Get options from select box\n    var my_options = $("#" + this.attr(\'id\') + \' option\');\n    // sort alphabetically\n    my_options.sort(function(a,b) {\n        if (a.text &gt; b.text) return 1;\n        else if (a.text &lt; b.text) return -1;\n        else return 0\n    })\n   //replace with sorted my_options;\n   $(this).empty().append( my_options );\n\n   // clearing any selections\n   $("#"+this.attr(\'id\')+" option").attr(\'selected\', false);\n}\n</code></pre>\n'}, {'answer_id': 7236274, 'author': 'João', 'author_id': 711756, 'author_profile': 'https://Stackoverflow.com/users/711756', 'pm_score': 1, 'selected': False, 'text': '<p>Remember: if you want to use context selector, just concatenate the ID will not work</p>\n\n<pre><code>$.fn.sort_select_box = function(){\n    var my_options = $("option", $(this));\n    my_options.sort(function(a,b) {\n        if (a.text &gt; b.text) return 1;\n        else if (a.text &lt; b.text) return -1;\n        else return 0\n    });\n    $(this).empty().append(my_options);\n}\n\n// Usando:\n$("select#ProdutoFornecedorId", $($context)).sort_select_box();\n</code></pre>\n'}, {'answer_id': 11196096, 'author': 'Juan Perez', 'author_id': 1480913, 'author_profile': 'https://Stackoverflow.com/users/1480913', 'pm_score': 2, 'selected': False, 'text': '<p>This is a better solution.\nDeclare a global function to JQuery</p>\n\n<pre><code>$.fn.sortSelect = function() {\n    var op = this.children("option");\n    op.sort(function(a, b) {\n        return a.text &gt; b.text ? 1 : -1;\n    })\n    return this.empty().append(op);\n}\n</code></pre>\n\n<p>And call the function from the code.</p>\n\n<pre><code>$("#my_select").sortSelect();\n</code></pre>\n'}, {'answer_id': 12307006, 'author': 'Tom Pietrosanti', 'author_id': 412074, 'author_profile': 'https://Stackoverflow.com/users/412074', 'pm_score': 4, 'selected': False, 'text': '<p>The solution I mentioned in my comment to @Juan Perez</p>\n\n<pre><code>$.fn.sortOptions = function(){\n    $(this).each(function(){\n        var op = $(this).children("option");\n        op.sort(function(a, b) {\n            return a.text &gt; b.text ? 1 : -1;\n        })\n        return $(this).empty().append(op);\n    });\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$("select").sortOptions();\n</code></pre>\n\n<p>This can still be improved on, but I didn\'t need to add any more bells or whistles :)</p>\n'}, {'answer_id': 59665960, 'author': 'Adambean', 'author_id': 1372355, 'author_profile': 'https://Stackoverflow.com/users/1372355', 'pm_score': 1, 'selected': False, 'text': '<p>A bit late but for what it\'s worth I\'ve implemented a more complex function you can include generically. It has a few options for varied output. It can also recurse into <code>&lt;OPTGROUP&gt;</code> tags based on their label.</p>\n\n<pre><code>$.fn.sortSelect = function(options){\n\n    const OPTIONS_DEFAULT = {\n        recursive:      true,   // Recurse into &lt;optgroup&gt;\n        reverse:        false,  // Reverse order\n        useValues:      false,  // Use values instead of text for &lt;option&gt; (&lt;optgruop&gt; is always label based)\n        blankFirst:     true,   // Force placeholder &lt;option&gt; with empty value first, ignores reverse\n    }\n\n    if (typeof options != "object" || null === options) {\n        options = OPTIONS_DEFAULT;\n    }\n\n    var sortOptions = function($root, $node, options){\n\n        if ($node.length != 1) {\n            return false;\n        }\n\n        if ($node[0].tagName != "SELECT" &amp;&amp; $node[0].tagName != "OPTGROUP") {\n            return false;\n        }\n\n        if (options.recursive) {\n            $node.children(\'optgroup\').each(function(k, v){\n                return sortOptions($root, $(v), options);\n            });\n        }\n\n        var $options        = $node.children(\'option, optgroup\');\n        var $optionsSorted  = $options.sort(function(a, b){\n\n            if (options.blankFirst) {\n                if (a.tagName == "OPTION" &amp;&amp; a.value == "") {\n                    return -1;\n                }\n\n                if (b.tagName == "OPTION" &amp;&amp; b.value == "") {\n                    return 1;\n                }\n            }\n\n            var textA = (a.tagName == "OPTION" ? (options.useValues ? a.value : a.text) : a.label);\n            var textB = (b.tagName == "OPTION" ? (options.useValues ? a.value : b.text) : b.label);\n\n            if (textA &gt; textB) {\n                return options.reverse ? -1 : 1;\n            }\n\n            if (textA &lt; textB) {\n                return options.reverse ? 1 : -1;\n            }\n\n            return 0;\n\n        });\n\n        $options.remove();\n        $optionsSorted.appendTo($node);\n\n        return true;\n\n    };\n\n    var selected = $(this).val();\n    var sorted = sortOptions($(this), $(this), {...OPTIONS_DEFAULT, ...options});\n    $(this).val(selected);\n\n    return sorted;\n\n};\n</code></pre>\n\n<p>You can then call the <code>sortSelect()</code> function on any <code>&lt;SELECT&gt;</code> tag, or just a single <code>&lt;OPTGROUP&gt;</code> to only sort a group\'s options.</p>\n\n<p>Example:</p>\n\n<pre><code>$(\'select\').sortSelect();\n</code></pre>\n\n<p>Reverse order using the "reverse" option:</p>\n\n<pre><code>$(\'select\').sortSelect({\n    reverse: true\n});\n</code></pre>\n\n<p>You could apply this to all selects automatically, perhaps only if they include an important class (e.g. "js-sort") with this:</p>\n\n<pre><code>$(\'select.js-sort\').each(function(k, v){\n    $(v).sortSelect();\n});\n</code></pre>\n'}, {'answer_id': 68092097, 'author': 'CARLOS AGUIRRE', 'author_id': 10980978, 'author_profile': 'https://Stackoverflow.com/users/10980978', 'pm_score': 0, 'selected': False, 'text': '<p>Seems jquery still is not particularly helpful enough for sorting options in a html select element.\nHere is some plain-plain javascript code for sorting options:</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>function sortOptionsByText(a,b) {\n  // I keep an empty value option on top, b.value comparison to 0 might not be necessary if empty value is always on top...\n  if (a.value.length==0 || (b.value.length&gt;0 &amp;&amp; a.text &lt;= b.text)) return -1; // no sort: a, b\n  return 1; // sort switches places: b, a\n}\nfunction sortOptionsByValue(a,b) {\n  if (a.value &lt;= b.value) return -1; // a, b\n  return 1; // b, a\n}\nfunction clearChildren(elem) {\n  if (elem) {\n    while (elem.firstChild) {\n      elem.removeChild(elem.firstChild);\n    }\n  }\n}\nfunction sortSelectElem(sel,byText) {\n  const val=sel.value;\n  const tmp=[...sel.options];\n  tmp.sort(byText?sortOptionsByText:sortOptionsByValue);\n  clearChildren(sel);\n  sel.append(...tmp);\n  sel.value=val;\n}</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>RACE: &lt;select id="list" size="6"&gt;\n  &lt;option value=""&gt;--PICK ONE--&lt;/option&gt;\n  &lt;option value="1"&gt;HUMANOID&lt;/option&gt;\n  &lt;option value="2"&gt;AMPHIBIAN&lt;/option&gt;\n  &lt;option value="3"&gt;REPTILE&lt;/option&gt;\n  &lt;option value="4"&gt;INSECTOID&lt;/option&gt;\n&lt;/select&gt;&lt;br&gt;\n&lt;button type="button" onclick="sortSelectElem(document.getElementById(\'list\'));"&gt;SORT LIST BY VALUE&lt;/button&gt;&lt;br&gt;\n&lt;button type="button" onclick="sortSelectElem(document.getElementById(\'list\'),true);"&gt;SORT LIST BY TEXT&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 69577409, 'author': 'lisandro', 'author_id': 2363940, 'author_profile': 'https://Stackoverflow.com/users/2363940', 'pm_score': 0, 'selected': False, 'text': '<p>With jquery this worked for me in Chrome in order to sort a select made from database unsorted elements.</p>\n<pre><code>$(document).ready(function(){\n    \n    var $list = $(&quot;#my_select&quot;);\n    var selected = $(&quot;#my_select&quot;).val(); //save selected value\n    \n    $list.children().detach().sort(function(a, b) {\n        return $(a).text().localeCompare($(b).text());\n      }).appendTo($list);  //do the sorting locale for latin chars\n    \n    $(&quot;#my_select&quot;).val(selected); //select previous selected value\n\n});\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/45888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1414/']