如何更优雅实现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
相关产品推荐
相关产品推荐

