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

如何使用jQuery或JavaScript按category降序、name升序排序数据

问题原因

  • 你连续两次调用sort方法是错误的:后一次排序会覆盖前一次的排序结果,无法实现「先按category排序、category相同时再按name排序」的多条件优先级效果
  • 你写的category降序排序函数逻辑实际是升序,和需求相反

解决方法

把两个排序规则合并到同一个排序函数里,优先判断category字段,category相等时再判断name字段:

var data = {
  0: {
    category: 'A',
    name: 'AA'
  },
  1: {
    category: 'B',
    name: 'BB'
  },
  2: {
    category: 'A',
    name: 'AB'
  },
  3: {
    category: 'A',
    name: 'BB'
  }
}

// 先把对象转成数组,无需额外用$()包裹为jQuery对象,原生数组的sort方法即可实现需求
var items = $.map(data, function (val) {
  return val;
});

// 合并多条件的排序函数
function multiSort(a, b) {
  // 先按category降序排列
  if (a.category !== b.category) {
    return a.category > b.category ? -1 : 1;
  }
  // category相同的情况下按name升序排列
  return a.name < b.name ? -1 : 1;
}

items.sort(multiSort);
console.log(items);

执行后得到的items数组顺序和你要求的预期输出完全一致:

[
  { category: 'B', name: 'BB' },
  { category: 'A', name: 'AA' },
  { category: 'A', name: 'AB' },
  { category: 'A', name: 'BB' }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:54:01