JavaScript move an item of an array to the front

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

    If you don't want to alter the existing array, you can use ES6 destructuring with the filter method to create a new copy while maintaining the order of the other items.

    const data = ["email", "role", "type", "name"];
    const newData = ['role', ...data.filter(item => item !== 'role')];
    

提交回复
热议问题