JavaScript move an item of an array to the front

前端 未结 17 937
终归单人心
终归单人心 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 21:00

    You can sort the array and specify that the value "role" comes before all other values, and that all other values are equal:

    var first = "role";
    data.sort(function(x,y){ return x == first ? -1 : y == first ? 1 : 0; });
    

    Demo: http://jsfiddle.net/Guffa/7ST24/

提交回复
热议问题