JavaScript move an item of an array to the front

前端 未结 17 803
终归单人心
终归单人心 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:52
    var i = -1;
    while (i < data.length) {
        if (data[i] === "role") {
            data.splice(i, 1);
            break;
        }
        i++;
    }
    data.unshift("role");
    

    indexOf only has limited browser support, not being recognized by IE7-8. So I wouldn't use it if I were you, even at the expense of a few lines' worth of code conciseness. You also want to put a semicolon at the end of the "unshift" statement. splice()'s first argument specifies the index to start removing elements, and the second argument specifies the number of arguments to remove.

    0 讨论(0)
  • 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().
    0 讨论(0)
  • 2020-12-12 20:54

    I would go with this ES6 solution. It doesn't mutate the original array(considering it's not nested), doesn't traverse through the array(filter) and you're not just limited to 0th index for shifting the array item.

    const moveArrayItem = (array, fromIndex, toIndex) => {
        const arr = [...array];
        arr.splice(toIndex, 0, ...arr.splice(fromIndex, 1));
        return arr;
    }
    
    
    const arr = ["a", "b", "c", "d", "e", "f", "g"];
    console.log(moveArrayItem(arr, 4, 0))
    // [ 'e', 'a', 'b', 'c', 'd', 'f', 'g' ]
    
    0 讨论(0)
  • 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);

    0 讨论(0)
  • 2020-12-12 20:57

    The cleanest solution in ES6 in my opinion:

    let data = ["email","role","type","name"];
    data = data.filter(item => item !== "role");
    data.unshift("role");
    
    0 讨论(0)
  • 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);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    0 讨论(0)
提交回复
热议问题