Given an array:
var myList = [ \'Normal\', \'Urgent\', \'Alert\', \'Casual\', \'Follow up\' ];
I want to output this list in say, a dropdown. I
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);
You could use filter to get the special values, sort the rest, and concatenate the parts:
var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];
myList = myList.filter( v => v === 'Urgent' ).concat(
myList.filter( v => v === 'Alert' ),
myList.filter( v => !['Alert','Urgent'].includes(v) ).sort());
console.log(myList);
var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];
console.log(['Urgent', 'Alert', ...myList.filter(item => item !== 'Urgent' && item !== 'Alert').sort()]);
It's best if you keep your prioritized elements separate from the main list, if you can't guarantee they will be present. I would filter those elements out, sort the rest, and concatenate the results with your special list.
var special = ["Urgent","Alert"];
var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];
myList = special.concat(myList.filter(function(el){ return special.indexOf(el) == -1; }).sort());
alert(myList);