How to sort an array in a unique order

后端 未结 4 2010
暗喜
暗喜 2021-01-28 10:03

Given an array:

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

I want to output this list in say, a dropdown. I

4条回答
  •  难免孤独
    2021-01-28 10:39

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

提交回复
热议问题