remove first element from array and return the array minus the first element
JavascriptJqueryArraysJavascript 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"
- How to remove the first array but return the array minus the first element
- 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.