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?
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?
Share Improve this question edited Aug 26, 2016 at 20:54 Barmar 784k57 gold badges548 silver badges659 bronze badges asked Aug 26, 2016 at 20:52 JekaJeka 1,7003 gold badges23 silver badges38 bronze badges 1- At starters, read Array.sort at MDN. – Teemu Commented Aug 26, 2016 at 20:56
2 Answers
Reset to default 7I 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);
Use an object that maps priority names to numbers, then sort based on that.
var priorities = {
low: 0,
high: 1,
critical: 2
};
var myArray = [{
priority: "low"
}, {
priority: "critical"
}, {
priority: "high"
}]
myArray.sort(function(a, b) {
return priorities[b.priority] - priorities[a.priority];
});
console.log(myArray);