如何根据嵌套对象数组属性是否含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
相关产品推荐
相关产品推荐

