Jeka Jeka - 1 year ago 83
Javascript Question

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?

Answer Source

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];


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download