bruh bruh - 1 year ago 64
Javascript Question

How to sort an array in a unique order

Given an array:

var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

I want to output this list in say, a dropdown. I want 'Urgent' to show up first, followed by 'Alert'. The rest should be sorted alphabetically.

I'm aware I can alphabetically sort the entire array with
but is there a way to sort this list to my unique requirements? I'm hoping this can be done as an array without converting it to an object and assigning priority identifiers - but I may be wrong.

Also, what if Urgent or Alert doesn't exist?

EDIT: Here is what I tried:

Answer Source

You could use an object for the sort order.

var array = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];

array.sort(function (a, b) {
    var order = { Urgent: -2, Alert: -1 };
    return (order[a] || 0) - (order[b] || 0) || a.localeCompare(b);


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