javascript - placing items at the beginning of an array -
javascript - placing items at the beginning of an array -
i got select element, multiple items. i'm supposed place values start '_' @ origin of list, ordered alphabetically. tried doing unshift() javascript method didn't work. there other way this?
html:
<select multiple="multiple"> <option>_c</option> <option>b</option> <option>_v</option> <option>a</option> </select>
script:
$(document).ready(function() { var = []; $('option').each(function() { a.push($(this).text()); }); $('option').each(function() { var v = $(this).text(); var s = v.substring(0,1); if (s == '_') { a.unshift($(this).text()); } }); a.sort(); (i = 0; < a.length; i++) { $('option').eq(i).text(a[i]); } });
it outputs following:
_c _c _v _v
as can see, scrambles values , losts reference ones without '_'.
alphabetically speaking, underscore has precedence on other characters, , automatically placed in front end using mutual .sort()
method, give right order:
class="snippet-code-js lang-js prettyprint-override">var = []; $('option').each(function() { a.push($(this).text()); }); = a.sort(); (i = 0; < a.length; i++) { $('option').eq(i).text(a[i]); }
class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select multiple="multiple"> <option>_c</option> <option>b</option> <option>_v</option> <option>a</option> </select>
edit
as discussed below, may better re-order elements, not values within them. also, there's room improvement on loops. so, here goes fancy way solve issue:
obs: jquery's .sort()
not yet officially supported.
class="snippet-code-js lang-js prettyprint-override">var select = $("select"); var opts = select.children("option"); select.append(opts.sort(function(a, b) { homecoming $(a).text() > $(b).text(); }));
class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select multiple="multiple"> <option>_c</option> <option>b</option> <option>_v</option> <option>a</option> </select>
javascript jquery arrays sorting selection
Comments
Post a Comment