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

如何将指定类型对象移至对象数组顶部并排序?含枚举方案

问题描述

现有如下对象数组:

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:31:17