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

如何更优雅实现JavaScript对象数组按size升序+color字母序排序?

问题描述

给定包含{"color":string,"size":int}的对象数组,要求先按size升序排序,若多个对象size相同,则按color字母序排序。现有实现代码如下:

//example:
let x = [{"color":"green" ,"size":42},{"color":"blue" ,"size":42},{"color":"red" ,"size":42},{"color":"blue" ,"size":41}];

//1st - sorting by size:
x=x.sort((a,b)=>a.size-b.size)

//2nd - find unique sizes.
const uniqueSizes = [...new Set(x.map(item => item.size))]; 

//3rd - group the initial array into individual arrays of same size
let grouped=[]
for (const size of uniqueSizes){
  let found=x.filter((f)=>f.size===size);
  grouped.push(found)
}
console.log(grouped)

//last - sort individual groups and print them.
for (const g of grouped){
  console.log(
    g.sort((a,b)=>a.color.localeCompare(b.color)).map(z=>`${z.size} ${z.color}`).join(`\n`)
  )
}

运行结果:

41 blue
42 blue
42 green
42 red

当前方案繁琐且存在冗余变量,分步处理也较为耗时,求更简洁优雅的实现方式?


优化实现

可以直接在一次sort操作中完成多条件排序,无需分组再二次排序,代码更简洁高效:

const x = [{"color":"green" ,"size":42},{"color":"blue" ,"size":42},{"color":"red" ,"size":42},{"color":"blue" ,"size":41}];

// 一次排序完成size升序 + color字母序
x.sort((a, b) => {
  // 先比较size,不等则直接返回差值
  if (a.size !== b.size) {
    return a.size - b.size;
  }
  // size相等时,按color字母序排序
  return a.color.localeCompare(b.color);
});

// 格式化输出
console.log(x.map(item => `${item.size} ${item.color}`).join('\n'));

优化点说明

  • 减少操作步骤:原方案分多步处理,现在仅需一次排序完成所有规则,避免了冗余的分组和二次排序操作
  • 降低时间复杂度:原方案中filter和多次sort会增加额外开销,一次排序的时间复杂度为O(n log n),效率更高
  • 代码更简洁:去掉了冗余的中间变量(uniqueSizes、grouped),逻辑更直观

运行结果与原代码完全一致:

41 blue
42 blue
42 green
42 red

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:43:10