JavaScript move an item of an array to the front

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

    My first thought would be:

    var data= ["email","role","type","name"];
    
    // if it's not there, or is already the first element (of index 0)
    // then there's no point going further:
    if (data.indexOf('role') > 0) {
        // find the current index of 'role':
        var index = data.indexOf('role');
        // using splice to remove elements from the array, starting at
        // the identified index, and affecting 1 element(s):
        data.splice(index,1);
        // putting the 'role' string back in the array:
        data.unshift('role');
    }
    
    console.log(data);
    

    To revise, and tidy up a little:

    if (data.indexOf('role') > 0) {
        data.splice(data.indexOf('role'), 1);
        data.unshift('role');
    }
    

    References:

    • Array.indexOf().
    • Array.prototype.splice().
    • Array.unshift().

提交回复
热议问题