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

Angular 16+ 如何按指定状态顺序[N-Op, Used, Unknown, Op]排序对象数组?

在Angular 16+中按自定义状态顺序排序对象数组

需求说明

需要按照指定的状态顺序 [N-Op, Used, Unknown, Op] 对对象数组进行排序,示例输入数据:

const stockList = [
    {
      'heading': 'SK',
      'status': 'N-Op',
    },
    {
      'heading': 'SKU',
      'status': 'Op',
    },
    {
      'heading': 'Uniliver',
      'status': 'Op',
    },
    {
      'heading': 'Bugati',
      'status': 'Unknown',
    },
    {
      'heading': 'Bugati',
      'status': 'N-Op',
    },
];

预期排序结果:

const stockList = [
    {
      'heading': 'SK',
      'status': 'N-Op',
    },
    {
      'heading': 'Bugati',
      'status': 'N-Op',
    },
    {
      'heading': 'Bugati',
      'status': 'Unknown',
    },
    {
      'heading': 'SKU',
      'status': 'Op',
    },
    {
      'heading': 'Uniliver',
      'status': 'Op',
    }
];

实现方法

步骤1:定义状态优先级映射

先创建状态到优先级序号的映射,让排序时能快速比较状态顺序:

// 自定义状态排序顺序
const statusOrder = ['N-Op', 'Used', 'Unknown', 'Op'];
// 生成状态优先级映射
const statusPriority: Record<string, number> = {};
statusOrder.forEach((status, index) => {
  statusPriority[status] = index;
});

步骤2:执行排序

如果不需要严格保留同状态元素的原始顺序,直接使用数组的sort()方法即可:

// 基础排序(注意:JS原生sort是不稳定排序,同状态元素顺序可能变化)
stockList.sort((a, b) => {
  return statusPriority[a.status] - statusPriority[b.status];
});

如果需要严格保留同状态元素的原始相对顺序(和示例结果完全一致),可以结合原始索引实现稳定排序:

// 1. 为每个元素添加原始索引
const indexedList = stockList.map((item, idx) => ({ ...item, originalIndex: idx }));

// 2. 先按状态优先级排序,优先级相同时按原始索引排序
indexedList.sort((a, b) => {
  const priorityDiff = statusPriority[a.status] - statusPriority[b.status];
  return priorityDiff !== 0 ? priorityDiff : a.originalIndex - b.originalIndex;
});

// 3. 移除临时添加的原始索引,得到最终排序后的数组
const sortedStockList = indexedList.map(({ originalIndex, ...rest }) => rest);

注意事项

  • 可以将排序逻辑封装成工具函数,方便在组件或服务中复用。
  • 如果数组中存在未定义的状态,建议在映射中设置默认值(比如statusPriority[status] ?? statusOrder.length),避免排序报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:26:14