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

如何使用Array.prototype.sort()按type、currency双属性自定义规则排序数组

实现方案

核心思路是将自定义优先级规则转换为可直接比较的数字权重,多属性排序时优先对比高优先级维度,差值不为0直接返回排序结果,差值为0再对比下一级维度即可。

完整代码

const accounts = [
  { id: 1, type: 'credit', currency: 'GBP' },
  { id: 2, type: 'debit', currency: 'EUR' },
  { id: 3, type: 'loan' },
  { id: 4, type: 'credit', currency: 'RUB' },
  { id: 5, type: 'credit', currency: 'RUB' },
  { id: 6, type: 'debit', currency: 'USD' },
  { id: 7, type: 'debit', currency: 'RUB' },
  { id: 8, type: 'external' },
  { id: 9, type: 'credit', currency: 'EUR' }
];

// 优先级映射表:数值越小,排序越靠前
const typePriority = {
  debit: 1,
  credit: 2,
  external: 3,
  loan: 4
}
const currencyPriority = {
  RUB: 1,
  USD: 2,
  EUR: 3,
  GBP: 4,
  default: 99 // 无currency字段的条目默认排在同类型最后
}

accounts.sort((a, b) => {
  // 优先对比type权重
  const typeDiff = typePriority[a.type] - typePriority[b.type]
  if (typeDiff !== 0) return typeDiff
  // type相同则对比currency权重
  const aCurrency = currencyPriority[a.currency] ?? currencyPriority.default
  const bCurrency = currencyPriority[b.currency] ?? currencyPriority.default
  return aCurrency - bCurrency
})

// 输出验证排序结果
console.log(accounts)

排序结果

执行后accounts的最终顺序符合要求:

[
  { id: 7, type: 'debit', currency: 'RUB' },
  { id: 6, type: 'debit', currency: 'USD' },
  { id: 2, type: 'debit', currency: 'EUR' },
  { id: 4, type: 'credit', currency: 'RUB' },
  { id: 5, type: 'credit', currency: 'RUB' },
  { id: 9, type: 'credit', currency: 'EUR' },
  { id: 1, type: 'credit', currency: 'GBP' },
  { id: 8, type: 'external' },
  { id: 3, type: 'loan' }
]

说明

  • 后续调整排序优先级仅需修改映射表的数值即可,无需改动比较逻辑,扩展性强
  • 若需将无currency字段的条目排在同类型最前,将currencyPriority.default的数值改为0即可
  • 若需要兼容低版本JS环境,可将空值合并运算符??替换为逻辑或运算符||

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:15:03