JavaScript move an item of an array to the front

前端 未结 17 938
终归单人心
终归单人心 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:56

    You could take the delta of the check with the wanted value at top.

    var data = ["email", "role", "type", "name"];
    
    data.sort((a, b) => (b === 'role') - (a === 'role'));
    
    console.log(data);

提交回复
热议问题