remove first element from array and return the array minus the first element

JavascriptJqueryArrays

Javascript Problem Overview


var myarray = ["item 1", "item 2", "item 3", "item 4"];

//removes the first element of the array, and returns that element.
alert(myarray.shift());
//alerts "item 1"

//removes the last element of the array, and returns that element.
alert(myarray.pop());
//alerts "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

Javascript Solutions


Solution 1 - Javascript

This should remove the first element, and then you can return the remaining:

var myarray = ["item 1", "item 2", "item 3", "item 4"];
    
myarray.shift();
alert(myarray);

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

var myarray = ["item 1", "item 2", "item 3", "item 4"];
  
alert(myarray.slice(1));

Solution 2 - Javascript

Why not use ES6?

 var myarray = ["item 1", "item 2", "item 3", "item 4"];
 const [, ...rest] = myarray;
 console.log(rest)

Solution 3 - Javascript

Try this

    var myarray = ["item 1", "item 2", "item 3", "item 4"];
    
    //removes the first element of the array, and returns that element apart from item 1.
    myarray.shift(); 
    console.log(myarray); 

Solution 4 - Javascript

This can be done in one line with lodash _.tail:

var arr = ["item 1", "item 2", "item 3", "item 4"];
console.log(_.tail(arr));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Solution 5 - Javascript

myarray.splice(1) will remove the first item from the array … and return the updated array (['item 2', 'item 3', 'item 4'] in your example).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Solution 6 - Javascript

You can use array.slice(0,1) // First index is removed and array is returned.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrownman RevivalView Question on Stackoverflow
Solution 1 - JavascriptJesper HøjerView Answer on Stackoverflow
Solution 2 - JavascriptTudor MorarView Answer on Stackoverflow
Solution 3 - JavascriptI'm GeekerView Answer on Stackoverflow
Solution 4 - JavascriptPenny LiuView Answer on Stackoverflow
Solution 5 - JavascriptbrynView Answer on Stackoverflow
Solution 6 - JavascriptHassan AbbasView Answer on Stackoverflow