How to sort an array in a unique order

后端 未结 4 1972
暗喜
暗喜 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);

    0 讨论(0)
  • 2021-01-28 10:49

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

    0 讨论(0)
  • 2021-01-28 10:54

    var myList = [ 'Normal', 'Urgent', 'Alert', 'Casual', 'Follow up' ];
    
    console.log(['Urgent', 'Alert', ...myList.filter(item => item !== 'Urgent' && item !== 'Alert').sort()]);

    0 讨论(0)
  • 2021-01-28 10:57

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

    0 讨论(0)
提交回复
热议问题