Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array of objects in JavaScript based on definite attribute value?

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.

like image 504
Lalit Avatar asked Nov 30 '25 11:11

Lalit


1 Answers

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; }
like image 136
Nina Scholz Avatar answered Dec 02 '25 01:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!