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

如何正确排序含重量范围字符串的JavaScript对象数组?

修复重量范围数组的排序问题

原代码的核心问题

  • 字符串截取逻辑错误:硬编码索引(substring(0,2)、substring(5))无法适配不同长度的数字,比如"3 - 6"的substring(5)会得到空字符串,转数字后为0,完全不符合预期。
  • 排序逻辑不严谨:原判断要求min和max同时大于才排序,忽略了仅min不同或仅max不同的情况,导致大量元素无法正确排序。
  • 数组原地修改:sort是原地排序方法,min和max指向同一个数组,后执行的排序会覆盖前一个的结果。

修正方案

  1. 可靠解析重量范围:用split(' - ')拆分字符串,确保正确提取最小和最大重量的数值。
  2. 复制数组避免覆盖:使用数组副本进行排序,保证两个排序结果独立。
  3. 合理的排序逻辑:先按最小重量排序,最小重量相同时再按最大重量排序。

修正后的代码

const arr =  [{weight : "4 - 5"}, {weight : "7 - 11"}, {weight : "20 - 25"}, {weight : "5 - 12"}, {weight : "3 - 6"}, {weight : "3 - 5"}];

// 解析重量字符串为数字对象的工具函数
const parseWeight = (weightStr) => {
  const [min, max] = weightStr.split(' - ').map(Number);
  return { min, max };
};

// 从小到大排序:先比min,min相同比max
const sortedAsc = [...arr].sort((a, b) => {
  const weightA = parseWeight(a.weight);
  const weightB = parseWeight(b.weight);
  if (weightA.min !== weightB.min) {
    return weightA.min - weightB.min;
  }
  return weightA.max - weightB.max;
});

// 从大到小排序:先比min,min相同比max
const sortedDesc = [...arr].sort((a, b) => {
  const weightA = parseWeight(a.weight);
  const weightB = parseWeight(b.weight);
  if (weightA.min !== weightB.min) {
    return weightB.min - weightA.min;
  }
  return weightB.max - weightA.max;
});

console.log('从小到大排序结果:', sortedAsc);
console.log('从大到小排序结果:', sortedDesc);

运行结果

从小到大排序结果: [
  { weight: '3 - 5' },
  { weight: '3 - 6' },
  { weight: '4 - 5' },
  { weight: '5 - 12' },
  { weight: '7 - 11' },
  { weight: '20 - 25' }
]
从大到小排序结果: [
  { weight: '20 - 25' },
  { weight: '7 - 11' },
  { weight: '5 - 12' },
  { weight: '4 - 5' },
  { weight: '3 - 6' },
  { weight: '3 - 5' }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:35:36