How to remove first element of an array in javascript?
-
var arr = [1,2,3,5,6]; I want to remove the 1st element of the array so that it becomes: var arr = [2,3,5,6]; How? Edit To extend this question, what if I want to remove the 2nd element of the array?
-
Answer:
Use the https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice function: var indexToRemove = 0; var numberToRemove = 1; arr.splice(indexToRemove, numberToRemove);
user198729 at Stack Overflow Visit the source
Other answers
arr.shift() works out of the box: arr = [1, 2, 3, 4, 5] arr.shift() alert(arr) // [2, 3, 4, 5]
Joseph Silvashy
Wrote a small article about inserting and deleting elements at arbitrary positions in Javascript Arrays. Here's the small snippet to remove an element from any position. This extends the Array class in Javascript and adds the remove(index) method. // Remove element at the given index Array.prototype.remove = function(index) { this.splice(index, 1); } So to remove the first item in your example, call arr.remove(): var arr = [1,2,3,5,6]; arr.remove(0); To remove the second item, arr.remove(1); Here's a tiny http://r0x0r.tumblr.com/post/304905664/javascript-arrays-custom-methods with insert and delete methods for Array class. Essentially this is no different than the other answers using splice, but the name splice is non-intuitive, and if you have that call all across your application, it just makes the code harder to read.
Anurag
arr.slice(begin[,end]) is non destructive, splice and shift will modify your original array
kiuma
arr=arr.slice(1);
ThatGuyYouKnow
Related Q & A:
- How to show the element from XML (SAXParser) to table?Best solution by Stack Overflow
- How to find button element on the page?Best solution by Stack Overflow
- How can I put element beside another? (Android?Best solution by stackoverflow.com
- How to dynamically create object properties from an array in Javascript?Best solution by nfriedly.com
- How can I remove an element in a repeated list?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.