所以我有这个通知对象数组,必须按严重性降序排序,即 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/