You need to enable JavaScript to run this app. 如何按ExpertiseSubCategory字段对对象数组进行字母顺序排序
优惠活动
大模型
产品
解决方案
定价
更多

如何按ExpertiseSubCategory字段对对象数组进行字母顺序排序

按对象数组的ExpertiseSubCategory字段实现字母序排序

待处理的原始对象数组

我手头有如下结构的对象数组,需要按规则完成排序:

const originalExpertiseList = [
  {ExpertiseId: "1Y", ExpertiseName: "Ad-Based Monetization", ExpertiseSubCategory: "Content & Information Services"},
  {ExpertiseId: "2", ExpertiseName: "Balance sheet businesses", ExpertiseSubCategory: null},
  {ExpertiseId: "3", ExpertiseName: "Brand Franchiser or Licenser", ExpertiseSubCategory: "Consumer Brands or IP"},
  {ExpertiseId: "4", ExpertiseName: "Branded retail", ExpertiseSubCategory: null},
  {ExpertiseId: "5", ExpertiseName: "Wholesale", ExpertiseSubCategory: "Consumer Brands or IP"}
]

需求说明

希望能够按照ExpertiseSubCategory字段对该数组执行字母顺序排序。

实现方案

实现过程需要重点处理两个细节:

  • 数组中存在ExpertiseSubCategory为null的条目,直接调用字符串比较逻辑会触发空值报错,需要提前对空值做兜底处理
  • 跨环境的字符串字母序比较,优先使用原生localeCompare方法,比直接用比较运算符的排序结果更符合通用的字符排序规则

具体实现代码

// 不修改原数组的排序写法
const sortedResult = [...originalExpertiseList].sort((itemA, itemB) => {
  // 对null值做空字符串兜底,可根据需求调整空值的排序位置
  const subCategoryA = itemA.ExpertiseSubCategory ?? ""
  const subCategoryB = itemB.ExpertiseSubCategory ?? ""
  return subCategoryA.localeCompare(subCategoryB)
})

排序效果说明

上述代码执行后:

  • 所有非空的ExpertiseSubCategory值会按字母正序排列,顺序为:Consumer Brands or IP → Content & Information Services
  • 子分类为null的条目,因为被兜底为空字符串,会排在非空条目的最前方
  • 如果需要把null值统一放到数组末尾,只需要将兜底的空字符串替换为排序权重最高的占位值(如"zzzzz")即可调整排序位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 11:36:06