views:

131

answers:

4
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?

+5  A: 

Use the splice function:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);
Gabriel McAdams
And the follow-on question: `arr.splice(1,1)` for the second element.
slebetman
But it doesn't work for this case:var arr = [[1,2,3]];arr[0].slice(1,1);arr[0]
splice, not slice
Gabriel McAdams
Oh,it works!Great!
+1  A: 

arr=arr.slice(1);

ThatGuyYouKnow
+8  A: 

array.shift() works out of the box:

arr = [1, 2, 3, 4, 5]
arr.shift()

alert(arr) // [2, 3, 4, 5]
Joseph Silvashy
This works, but will only remove the first element in the array.
Gabriel McAdams
@Gabriel: wasn't exactly that the question? I prefer `shift()` to `splice(..., ...)` since it is much more explicit, direct.
Bruno Reis
He asked two separate questions in my opinion, `shift()` solves the original. there are a multitude of ways to solve the second, `splice` being the best.
Joseph Silvashy
+2  A: 

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 article 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