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

如何在Angular/TypeScript中按对象首列数值升序排序数组?

Angular/TypeScript 按对象首列排序实现方案

需求说明

现有一组对象数组,需按每个对象的首列(示例中为time字段)进行升序排序,技术栈为Angular/TypeScript。

原始数据

[
    {
        time: 1000.189,
        other: 100 
    },
    {
        time: 1023.189 ,
        other: 105 
    },
    {
        time: 999.189,
        other: 100  
    }
]

期望排序结果

[
    {
        time: 999.189,
        other: 100  
    },
    {
        time: 1000.189,
        other: 100 
    },
    {
        time: 1023.189,
        other: 105 
    }
]

实现方案

1. 已知首列字段名(如time)的情况

直接利用数组sort方法,结合TypeScript类型定义实现类型安全的排序:

// 定义数据类型
interface DataItem {
  time: number;
  other: number;
}

// 原始数据
const originalData: DataItem[] = [
  { time: 1000.189, other: 100 },
  { time: 1023.189, other: 105 },
  { time: 999.189, other: 100 }
];

// 升序排序(用扩展运算符创建数组副本,避免修改原数据)
const sortedData = [...originalData].sort((a, b) => a.time - b.time);
  • [...originalData]创建数组副本,避免sort原地修改原数据
  • a.time - b.time实现升序,需降序则改为b.time - a.time

2. 动态获取首列字段名的情况

如果不确定对象的首列字段名,可通过Object.keys动态提取第一个属性:

// 通用数据类型
interface DynamicDataItem {
  [key: string]: number | string;
}

const originalDynamicData: DynamicDataItem[] = [
  { time: 1000.189, other: 100 },
  { time: 1023.189, other: 105 },
  { time: 999.189, other: 100 }
];

// 获取对象的第一个属性名
const getFirstField = (obj: DynamicDataItem) => Object.keys(obj)[0];

// 动态按首列排序
const sortedDynamicData = [...originalDynamicData].sort((a, b) => {
  const firstField = getFirstField(a);
  // 若首列为字符串类型,替换为 a[firstField].localeCompare(b[firstField])
  return (a[firstField] as number) - (b[firstField] as number);
});
  • Object.keys(obj)[0]提取对象的第一个属性名
  • 若首列为字符串类型,需用localeCompare方法替代数字减法,避免排序逻辑错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:25:33