gpt4 book ai didi

javascript - 如何根据确定的属性值对 JavaScript 中的对象数组进行排序?

转载 作者:行者123 更新时间:2023-11-28 14:56:57 25 4
gpt4 key购买 nike

所以我有这个通知对象数组,必须按严重性降序排序,即 Error > Warning > Information

示例:

var notificationArray = [ {
code : "103",
severity : "Error"
}, {
code : "104",
severity : "Information"
}, {
code : "109",
severity : "Error"
}, {
code : "403",
severity : "Warning"
}, {
code : "510",
severity : "Information"
}, {
code : "114",
severity : "Warning"
}, {
code : "144",
severity : "Error"
}, {
code : "413",
severity : "Warning"
} ];

确保该数组始终根据严重性排序的最简单方法是什么?

附注还有其他线程对对象数组进行排序,但我最发现的是 unicode 排序,而不是通过与固定值进行比较来排序。如果我发布了重复的问题,请道歉。

最佳答案

您可以使用订单对象对严重性的优先级进行排序。

var notificationArray = [{ code: "103", severity: "Error" }, { code: "104", severity: "Information" }, { code: "109", severity: "Error" }, { code: "403", severity: "Warning" }, { code: "510", severity: "Information" }, { code: "114", severity: "Warning" }, { code: "144", severity: "Error" }, { code: "413", severity: "Warning" }, { code: "131", severity: "Error"}],
order = { Error: 1, Warning: 2, Information: 3 };

notificationArray.sort(function (a, b) {
return order[a.severity] - order[b.severity];
});

console.log(notificationArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何根据确定的属性值对 JavaScript 中的对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42533823/

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