2

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?

1
  • At starters, read Array.sort at MDN. Commented Aug 26, 2016 at 20:56

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

this should have been accepted answer from beginning thanks
Premature optimizations.... (a, b) => sort.indexOf(a.priority) - sort.indexOf(b.priority) would be much simpler.
@georg, i am not a fan of indexOf.
5

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

2 Comments

Not an arbitrary sort, though.
The associations between priority names and values in the object are arbitrary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.