So I have this array of notification objects that has to be sorted in decreasing order of severity i.e. Error > Warning > Information.
Example:
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"
} ];
What's the easiest way to make sure this array is always sorted based on severity?
P.S. There are other threads on sorting an array of objects but what I mostly found is unicode sorting and not sorting by comparing against a fixed value. Apologies if I posted a duplicate question.
You could sort with an order object for the priority of severity.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With