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

如何根据嵌套对象数组属性是否含stopped及id值排序对象数组

JavaScript 对象数组多条件排序实现

排序规则

  • 第一优先级:元素的嵌套数组things中存在status为stopped的项,对应元素排在最前方
  • 第二优先级:同优先级元素按id字段升序排列

实现代码

直接使用JS内置的Array.sort()方法即可实现需求:

const arr = [{
        id: 1,
        things: [{
                thing_id: 1,
                status: 'started',
            },
            {
                thing_id: 1,
                status: 'started',
            },
        ],
    },
    {
        id: 2,
        things: [{
                thing_id: 1,
                status: 'started',
            },
            {
                thing_id: 1,
                status: 'started',
            },
            {
                thing_id: 1,
                status: 'stopped',
            },
        ],
    },
    {
        id: 3,
        things: [{
                thing_id: 1,
                status: 'started',
            },
            {
                thing_id: 1,
                status: 'started',
            },
            {
                thing_id: 1,
                status: 'started',
            },
            {
                thing_id: 1,
                status: 'started',
            },
        ],
    }
]

const sortedArr = arr.sort((a, b) => {
  // 计算第一维度排序权重:存在stopped项权重为0,否则为1
  const aWeight = a.things.some(item => item.status === 'stopped') ? 0 : 1
  const bWeight = b.things.some(item => item.status === 'stopped') ? 0 : 1
  // 第一维度权重不同时按权重排序
  if (aWeight !== bWeight) {
    return aWeight - bWeight
  }
  // 权重相同时按id升序排序
  return a.id - b.id
})

console.log(sortedArr)

输出结果

运行代码得到的结果和需求的期望输出完全一致:

[{
  id: 2,
  things: [
    { thing_id: 1, status: 'started' },
    { thing_id: 1, status: 'started' },
    { thing_id: 1, status: 'stopped' }
  ]
}, {
  id: 1,
  things: [
    { thing_id: 1, status: 'started' },
    { thing_id: 1, status: 'started' }
  ]
}, {
  id: 3,
  things: [
    { thing_id: 1, status: 'started' },
    { thing_id: 1, status: 'started' },
    { thing_id: 1, status: 'started' },
    { thing_id: 1, status: 'started' }
  ]
}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:45:06