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

如何按照另一数组的对象顺序对数组对象排序,需对比多个属性?

需求说明

现有两个对象数组arrX和arrY,需要将arrY的对象按照arrX的type取值顺序排序,type属性不在arrX的type取值范围内的对象统一排在末尾,比如示例中的type: 'X'类对象。

示例输入

const arrX = [
  {type: 'C', category: 'CAT2'},
  {type: 'A', category: 'CAT1'},
  {type: 'B', category: 'CAT3'},
]    

const arrY = [
  {type: 'B', category: 'CAT3'},
  {type: 'A', category: 'CAT1'},
  {type: 'C', category: 'CAT2'},
  {type: 'B', category: 'CAT3'},
  {type: 'A', category: 'CAT1'},
  {type: 'X', category: 'CAT4'},
  {type: 'B', category: 'CAT2'},
  {type: 'X', category: 'CAT4'},
  {type: 'X', category: 'CAT5'},
  {type: 'A', category: 'CAT1'},
  {type: 'C', category: 'CAT2'}, 
]

预期输出(已修正原笔误)

按照需求规则,所有在arrX中存在的type对应对象全部排在未知type对象之前,修正后正确预期如下:

const sortedArr = [
  {type: 'C', category: 'CAT2'},
  {type: 'C', category: 'CAT2'},
  {type: 'A', category: 'CAT1'},
  {type: 'A', category: 'CAT1'},
  {type: 'A', category: 'CAT1'},
  {type: 'B', category: 'CAT3'},
  {type: 'B', category: 'CAT3'},
  {type: 'B', category: 'CAT2'},
  {type: 'X', category: 'CAT4'},
  {type: 'X', category: 'CAT4'},
  {type: 'X', category: 'CAT5'}, 
]

最优实现方案

实现思路

  1. 先基于arrX生成type到排序权重的映射表,未知type的默认权重设为无穷大,保证所有未知type自动排在末尾
  2. 调用数组原生sort方法,基于映射表的权重值排序即可

代码实现

// 生成type对应权重的映射表
const typeWeightMap = new Map(arrX.map((item, index) => [item.type, index]))
// 对arrY排序
const sortedY = arrY.sort((a, b) => {
  const weightA = typeWeightMap.has(a.type) ? typeWeightMap.get(a.type) : Infinity
  const weightB = typeWeightMap.has(b.type) ? typeWeightMap.get(b.type) : Infinity
  return weightA - weightB
})

方案优势

  • 时间复杂度低:生成映射表耗时为O(n)(n为arrX长度),排序耗时为O(m log m)(m为arrY长度),整体效率远高于排序时每次遍历arrX查找权重的实现
  • 代码简洁易维护,后续调整排序规则仅需修改映射表生成逻辑即可
  • 无需硬编码特殊type值,所有不在arrX中的type都会自动排在末尾,适配性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 20:24:07