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

如何在TypeScript中对JSON数组按label字段实现自定义排序

TypeScript 实现按label字段年龄区间排序方案

你给出的示例数组写法有语法问题,JS/TS数组不需要写索引前缀,正确的原始数据格式如下:

const Data: {label: string, value: number}[] = [
    { label: "Adults - 35 to 64", value: 38.2 },
    { label: "Young Adult- 16 to 34", value: 20.76 },
    { label: "Senior - 65+", value: 41.04 }
];

实现步骤

核心逻辑是从label字段中提取年龄区间的起始值,按起始值升序排列即可得到你要的结果:

  1. 先定义数据类型(TS类型校验必填)
interface AgeItem {
    label: string;
    value: number;
}
const originalData: AgeItem[] = [
    { label: "Adults - 35 to 64", value: 38.2 },
    { label: "Young Adult- 16 to 34", value: 20.76 },
    { label: "Senior - 65+", value: 41.04 }
];
  1. 编写排序逻辑
// 提取label中第一个数字作为排序权重
const getAgeStart = (label: string): number => {
    const match = label.match(/\d+/);
    return match ? Number(match[0]) : 0;
}

// 排序:如果不想修改原数组,先做浅拷贝再排序
const sortedData = [...originalData].sort((a, b) => {
    return getAgeStart(a.label) - getAgeStart(b.label);
});
  1. 输出的sortedData就是你要的结果:
[
    { label: "Young Adult- 16 to 34", value: 20.76 },
    { label: "Adults - 35 to 64", value: 38.2 },
    { label: "Senior - 65+", value: 41.04 }
]

注意事项

  • 内置的Array.sort()是原地排序,直接调用会修改原数组,对原始数据有保留需求的一定要先拷贝再排序
  • 正则匹配的逻辑适配你当前所有label的格式,只要label里第一个出现的数字是区间起始年龄就可以正常工作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:24:03