如何将指定类型对象移至对象数组顶部并排序?含枚举方案
问题描述
现有如下对象数组:
var obj = [ { name: "name1", type: 4 }, { name: "name6", type: 2 }, { name: "name2", type: 5 }, { name: "name3", type: 1 }, { name: "name5", type: 2 }, { name: "name4", type: 3 } ]
需要将其排序为:type为2或3的对象置于数组顶部,且顶部对象按name字段排序,最终得到如下结果:
var obj = [ { name: "name4", type: 3 }, { name: "name5", type: 2 }, { name: "name6", type: 2 }, { name: "name1", type: 4 }, { name: "name2", type: 5 }, { name: "name3", type: 1 } ]
同时需要提供当type为枚举类型(示例如下)时的实现方案:
export enum Types { Type0 = 0, Type1 = 1, // ...其他枚举值 }
实现方案
一、普通数字类型type的实现
利用数组的sort()方法自定义排序逻辑,核心分两步:先区分优先级,再对同优先级元素按name排序。
代码示例:
// 先复制原数组,避免修改原数据 const sortedObj = [...obj].sort((a, b) => { // 标记元素是否属于高优先级组(type为2或3) const isHighPriorityA = [2, 3].includes(a.type); const isHighPriorityB = [2, 3].includes(b.type); // 高优先级元素排在前面 if (isHighPriorityA && !isHighPriorityB) return -1; if (!isHighPriorityA && isHighPriorityB) return 1; // 同优先级时,按name字段的字典序排序 return a.name.localeCompare(b.name); });
二、枚举类型type的实现
如果type是枚举类型,只需将判断条件中的数字替换为枚举成员即可,既保证类型安全,也避免硬编码数字带来的维护问题。
假设枚举定义如下:
export enum Types { Type0 = 0, Type1 = 1, Type2 = 2, Type3 = 3, Type4 = 4, Type5 = 5 }
对应的排序代码:
const sortedObj = [...obj].sort((a, b) => { const isHighPriorityA = [Types.Type2, Types.Type3].includes(a.type); const isHighPriorityB = [Types.Type2, Types.Type3].includes(b.type); if (isHighPriorityA && !isHighPriorityB) return -1; if (!isHighPriorityA && isHighPriorityB) return 1; return a.name.localeCompare(b.name); });
内容的提问来源于stack exchange,提问作者Stranger
相关产品推荐
相关产品推荐

