如何正确对select下拉框的字母数字选项按复合字符串规则排序?
Fixing Alphanumeric Select Option Sorting Issue
The core problem here is that your current sorting logic uses lexicographical (string-based) comparison, which treats numbers as sequences of characters instead of actual numerical values. That’s why "1024kbps" ends up before "256kbps"—the string "1024" starts with "1", which is lex smaller than "2" in "256", even though 1024 is a larger number.
To fix this, we need to break down each option’s text into meaningful parts, then sort by those parts logically. Here’s how to adjust your code:
var options = $('select.whatever option'); var arr = options.map(function (_, o) { const optionText = $(o).text(); // Split text into prefix (e.g., H123) and bitrate segment (e.g., 128kbps) const [prefix, bitratePart] = optionText.split('-'); // Extract numerical value from the bitrate string const bitrate = parseInt(bitratePart.replace('kbps', ''), 10); return {t: optionText, v: o.value, prefix: prefix, bitrate: bitrate}; }).get(); // Custom sort logic: first compare prefixes, then numerical bitrate arr.sort(function (o1, o2) { // Sort by prefix first (lex order works here since prefixes follow a consistent pattern) if (o1.prefix !== o2.prefix) { return o1.prefix > o2.prefix ? 1 : -1; } // If prefixes match, sort by the numerical bitrate value return o1.bitrate - o2.bitrate; }); // Re-apply sorted options to the select element options.each(function (i, o) { o.value = arr[i].v; $(o).text(arr[i].t); });
Key improvements explained:
- Parsing options: We split each option text on the
-to isolate the prefix (likeH123) and the bitrate string. We then strip the "kbps" suffix and convert the remaining text to an integer, so we can compare values numerically. - Targeted sorting:
- First, we sort by the prefix (lex order works here because your prefixes follow a consistent
HXXXpattern). - When prefixes are identical, we use numerical subtraction to sort by bitrate—this ensures 128 < 256 < 512 < 1024, which matches your desired order.
- First, we sort by the prefix (lex order works here because your prefixes follow a consistent
- Preserving original values: We keep track of the original option values just like your original code, so we don’t lose any associated data when reordering.
Running this code will produce the exact sorted select options you’re expecting.
内容的提问来源于stack exchange,提问作者Evgeny
相关产品推荐
相关产品推荐

