You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对SelectOption按value值0-9-A-Z顺序排序并固定首选项

SelectOption数组排序实现方案
  • 核心逻辑为「固定项提前拆分 + 剩余项自定义排序」,避免固定项被排序逻辑影响
  • 排序规则直接通过JS内置的localeCompare方法实现,无需手动写复杂的字符判断逻辑
  • 最终将固定项拼接在排序后的数组头部即可

代码示例(TypeScript)

interface SelectOption {
  key: string | number;
  value: string;
}

const processSelectOptions = (rawOptions: SelectOption[]): SelectOption[] => {
  // 提取首位固定选项
  const fixedFirstOption = rawOptions.find(opt => opt.value === 'Select Description');
  // 过滤出需要排序的剩余选项
  const sortableOptions = rawOptions.filter(opt => opt.value !== 'Select Description');

  // 按0-9-A-Z规则排序
  sortableOptions.sort((a, b) => {
    return a.value.localeCompare(b.value, 'en', {
      numeric: true, // 数字按数值顺序排序,优先于字母
      caseFirst: 'upper' // 大写字母排序优先级高于小写,符合A-Z顺序
    })
  })

  // 拼接返回结果
  return fixedFirstOption ? [fixedFirstOption, ...sortableOptions] : sortableOptions;
}

代码示例(原生JavaScript)

如果不需要TS类型支持,可使用以下兼容写法:

function processSelectOptions(rawOptions) {
  const fixedFirstOption = rawOptions.find(opt => opt.value === 'Select Description');
  const sortableOptions = rawOptions.filter(opt => opt.value !== 'Select Description');

  sortableOptions.sort(function(a, b) {
    return a.value.localeCompare(b.value, 'en', {
      numeric: true,
      caseFirst: 'upper'
    })
  })

  return fixedFirstOption ? [fixedFirstOption].concat(sortableOptions) : sortableOptions;
}

如果要兼容极低版本浏览器不支持localeCompare参数的场景,可以手动判断字符类型,通过ASCII码比较实现排序,数字的ASCII码范围为48-57,大写字母为65-90,小写字母为97-122,按优先级排序即可。

内容的提问来源于stack exchange,提问作者Alexia Ribeiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:09:03