JavaScript move an item of an array to the front

前端 未结 17 919
终归单人心
终归单人心 2020-12-12 20:15

I want to check if an array contains \"role\". If it does, I want to move the \"role\" to the front of the array.

var data= [\"ema         


        
17条回答
  •  庸人自扰
    2020-12-12 20:57

    Using lodash _.sortBy. If the item is role, it will be sorted first, otherwise second. This works fine too if there is no role

    var data = ["email", "role", "type", "name"];
    
    var sorted = _.sortBy(data, function(item) {
      return item === 'role' ? 0 : 1;
    });
    
    console.log(sorted);

提交回复
热议问题