JavaScript move an item of an array to the front

前端 未结 17 802
终归单人心
终归单人心 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')];
    
    0 讨论(0)
  • 2020-12-12 20:43

    To check whether an item exists in an array you should to use .includes() instead of in (as already noted here, in is for properties in objects).

    This function does what you are looking for: (removes the item from the position it is in and reads in front)

       data = ["email","role","type","name"];
       moveToFirst("role", data)
        
       function moveToFirst(s, r){
          if (r.includes(s)){
            r.splice(r.indexOf(s),1);
            r.unshift(s);
          } 
        }
        
        console.log(data)

    0 讨论(0)
  • 2020-12-12 20:43
    1. the in operator is about properties, not about items in arrays. See How do I check if an array includes an object in JavaScript? for what to use else.
    2. You're missing braces around the two (!) statements in your if-block
    3. I'm not sure whether that .remove() function you're using does take an index of an item.
    0 讨论(0)
  • 2020-12-12 20:47

    Similar to @Tandroid's answer but a more general solution:

    const putItemsFirst = ({ findFunction, array }) => [
        ...array.filter(findFunction), 
        ...array.filter(signer => !findFunction(signer)),
    ]; 
    

    Can be used like this

    putItemsFirst({ 
        array: ["email","role","type","name"], 
        findFunction: item => item === 'role',
    })
    

    Something similar to this is what I ended up using,

    0 讨论(0)
  • 2020-12-12 20:47
    var data= ["email","role","type","name"];
    if ("role" in data) data.splice(data.indexOf("role"),1); data.unshift("role");
    data;
    
    0 讨论(0)
  • 2020-12-12 20:52
    let data = [0, 1, 2, 3, 4, 5];
    let index = 3;
    data.unshift(data.splice(index, 1)[0]);
    // data = [3, 0, 1, 2, 4, 5]
    
    0 讨论(0)
提交回复
热议问题