Search code examples
javascriptarrays

How can I remove the first element of an array and return the rest?


const array = ["item 1", "item 2", "item 3", "item 4"];

// removes the first element of the array, and returns that element.
console.log(array.shift());
// prints "item 1"

//removes the last element of the array, and returns that element.
console.log(array.pop());
// prints "item 4"

  1. How to remove the first array but return the array minus the first element?

  2. In my example I should get "item 2", "item 3", "item 4" when I remove the first element?


Solution

  • The .shift() method removes the first element of an array. Then you can return the remaining:

    const array = ["item 1", "item 2", "item 3", "item 4"];
    array.shift();
    
    console.log(array);

    As others have suggested, you could also use slice(1):

    const array = ["item 1", "item 2", "item 3", "item 4"];
      
    console.log(array.slice(1));