bruh bruh - 1 month ago 8
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
myList.sort()
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: https://jsfiddle.net/reala/rqacrz0k/

Answer

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

console.log(array);