gpt4 book ai didi

angular - Typescript 按状态排序列表(字符串值)

转载 作者:行者123 更新时间:2023-12-05 00:57:52 29 4
gpt4 key购买 nike

我需要按状态对项目列表进行排序,但我不确定应该采用哪种方法,是创建比较器还是某种排序技术?lodash 会在这里工作吗?

示例输入列表:

[
{id: 1, name: "name1", status: "Failed"},
{id: 2, name: "name2", status: "Success"},
{id: 3, name: "name3", status: "In progress"},
{id: 4, name: "name4", status: "Reserved"},
{id: 5, name: "name5", status: "Pending"}
]

以失败 -> 进行中 -> 保留 -> 待处理 -> 成功排序的示例排序列表(输出)

[
{id: 1, name: "name1", status: "Failed"},
{id: 3, name: "name3", status: "In progress"},
{id: 4, name: "name4", status: "Reserved"},
{id: 5, name: "name5", status: "Pending"}
{id: 2, name: "name2", status: "Success"},
]

我使用的堆栈是 Angular + Typescript。

编辑:列表有点大,通常大约 15k 行。

最佳答案

您可以根据其他数组中的值对数组进行排序:

let sortOrder = ['Failed', 'In progress', 'Reserved', 'Pending', 'Success'];
let array = [
{ id: 1, name: "name1", status: "Failed" },
{ id: 2, name: "name2", status: "Success" },
{ id: 3, name: "name3", status: "In progress" },
{ id: 4, name: "name4", status: "Reserved" },
{ id: 5, name: "name5", status: "Pending" }
];

array.sort((a, b) => {
return sortOrder.indexOf(a.status) - sortOrder.indexOf(b.status);
});

console.log(array);

关于angular - Typescript 按状态排序列表(字符串值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59574334/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com