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

如何在JavaScript中按指定规则对嵌套数组对象的子数组排序

按自定义规则排序对象数组的子数组

我有一个对象数组,需要用JavaScript按特定条件排序——对每个对象的others子数组依据tariffId排序:固定tariffId为7204的元素排在最后,其余元素按tariffId升序排列。

原数组

var arrobj = [
  {id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7204}, {place: "IN", tariffId:7203} ] },
  {id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7204}, {place: "IN", tariffId:7205} ] },
  {id:1, others: [ {place: "IN", tariffId:7202}, {place: "IN", tariffId:7204}, {place: "IN", tariffId:7201} ] }
]

期望输出

[
  {id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7203}, {place: "IN", tariffId:7204} ] },
  {id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7205}, {place: "IN", tariffId:7204} ] },
  {id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7202}, {place: "IN", tariffId:7204} ] }
]

我尝试过的代码

var result = arrobj.map(e =>
 e.others.sort((a,b)=> a-b).map(i => i))
;

解决方案

你之前的代码存在两个问题:一是直接对对象a和b做减法会得到NaN,无法正确排序;二是没有处理tariffId=7204的元素需要排在最后的逻辑。以下是符合需求的代码:

const result = arrobj.map(item => {
  // 复制子数组避免修改原数组(若无需保留原数组,可直接用item.others.sort)
  const sortedOthers = [...item.others].sort((a, b) => {
    // 优先处理7204排最后的规则
    if (a.tariffId === 7204) return 1;
    if (b.tariffId === 7204) return -1;
    // 其余元素按tariffId升序排列
    return a.tariffId - b.tariffId;
  });
  // 返回新对象,保留原属性并替换排序后的子数组
  return { ...item, others: sortedOthers };
});

console.log(result);

代码说明

  1. 遍历数组:用map遍历原数组,确保每个对象的others子数组都被处理;
  2. 排序逻辑:
    • 若当前元素a的tariffId是7204,返回1让它排在后面;
    • 若对比元素b的tariffId是7204,返回-1让a排在前面;
    • 其他情况用a.tariffId - b.tariffId实现升序排序;
  3. 避免修改原数组:通过扩展运算符[...item.others]复制子数组,再进行排序,防止原数组被意外修改(若业务允许修改原数组,可省略复制步骤)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 05:36:37