Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Arbitrary sort array based on values of a field

So I have an array of object which looks like this:

var myArray = [{priority : "low"}, {priority: "critical"}, {priority: "high"}]

I need to sort in this way: 1)Critical, 2) High and 3) Low.

how can this be done?

like image 998
Jeka Avatar asked Jun 14 '26 21:06

Jeka


1 Answers

I suggest to use an object for the storing of the sort order.

If you need a default value for sorting, you could use a value for sorting unknown priority to start or to the end.

var sort = ['critical', 'high', 'low'],
    defaultValue = Infinity,
    sortObj = {},
    myArray = [{ priority: "unknown" }, { priority: "low" }, { priority: "critical" }, { priority: "high" }];

sort.forEach(function (a, i) { sortObj[a] = i + 1; });

myArray.sort(function (a, b) {
    return (sortObj[a.priority] || defaultValue) - (sortObj[b.priority] || defaultValue);
});
	
console.log(myArray);
like image 123
Nina Scholz Avatar answered Jun 17 '26 11:06

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!