Sort an array in the same order of another array

前端 未结 4 1106
长发绾君心
长发绾君心 2020-12-06 07:19

I have a few arrays of 50+ names like this.

[\"dan\", \"ryan\", \"bob\", \"steven\", \"corbin\"]
[\"bob\", \"dan\", \"steven\", \"corbin\"]

4条回答
  •  天命终不由人
    2020-12-06 07:50

    I had the same issue now and I tried a bit different approach. It does not sort the arrays but filtering the order-list according to sorting-lists so it has got some limitations but for my needs it's event better because it gets rid of incorrect values from sorted list:

    • if sorting-list has got doubled value, it will occure just once in sorted list
    • if sorting-list has got item which is not included in order-list, it will not appear in sorted list

    function sortOrder(getOrder,getArr){
      return getOrder.filter(function(order){
        return getArr.some(function(list){
          return order === list;
        });
      });
    }
    
    //arrays
    var order = ["ryan", "corbin", "dan", "steven", "bob"];
    var arA = ["dan", "ryan", "bob", "steven", "corbin"];
    var arB = ["bob", "dan", "steven", "corbin"];
    var arC = ["bob","ryan"];
    var arD = ["bob","bob","corbin"]; //remove repetition
    var arE = ["unrecognizedItem","corbin","steven","ryan"]; //remove the item not included in order array
    
    //print results
    document.body.innerHTML = sortOrder(order,arA)+'
    '; document.body.innerHTML += sortOrder(order,arB)+'
    '; document.body.innerHTML += sortOrder(order,arC)+'
    '; document.body.innerHTML += sortOrder(order,arD)+'
    '; document.body.innerHTML += sortOrder(order,arE)+'
    ';

提交回复
热议问题