Updated March 10th, 2009
It turns out this is probably not the best way to do it. As per the comments below, be careful using the delete command as it will only set the element to undefined (the length of the array won’t be shortened. I considered deleting this post, but I think it may still be useful in that it helps clarify the difference between slice and delete.
Original post starts here…
If you search for this topic you’ll find that this can be accomplished using the splice function.
MyArray.splice(3, 1);
This was how I was doing it for a while, but I just recently discovered a simpler method.
delete MyArray[3]
Hope this helps,
Hillel
Seems after using delete, the length still remains the same…
delete MyArray[3];
MyArray.length -=1;
That does the trick.
After further testing…My above solution will not work.
From livedocs:
“The delete operator sets the value of an array element to undefined, but it does not remove the element from the array.”
So splice is the way.
Peter,
Thanks, you’re absolutely right. I didn’t discover that fact until after I had written the post. I’ve added an update to the post to reflect this additional piece of info.
Best,
Hilllel
It’s still useful in fact, when you do simply need to set the value to undefined. Then using operations like for example .join() will ignore the value.
Also, this works much better than splice() if you’re altering the array in a for each loop. If you splice() in a for each, you have to be careful with the positioning of the elements. Not so with delete, because the indexes remain intact.
Of course this still applies only if you can live with the indices being off.
I think slice() removes from an array, whereas splice() (which you cited up top) adds to it.
I apologize, it was indeed splice. 🙂
Crystal,
Strange timing…. I actually just made the mistake of using the wrong one in my code. It took me quite a while to spot the bug.
Best,
Hillel
I like this blog very much, Its a real nice post to read and get information.