Friday, September 23, 2011

Javascript: remove item from array

DON’T
Unfortunately the most obvioous solution leaves a “hole” in the array :-(.
>>> var list = [4,5,6];
>>> delete list[1];
true
>>> list
[4, undefined, 6]
Sad, but understandable.

DO
So do it right and use splice().
>>> var list = [4,5,6];
>>> list.splice(1, 1); // Remove one element, returns the removed ones.
[5]
>>> list
[4, 6]


Useful DO
Actually, what I mostly need is: remove a certain value from an array.
I.e. I have some list of visible IDs and I want to remove one because it’s not visible anymore. So just extend the above example a bit.
>>> var visibleIds = [4,5,6];
>>> var idx = visibleIds.indexOf(5); // Find the index
>>> if(idx!=-1) visibleIds.splice(idx, 1); // Remove it if really found!
[5]
>>> visibleIds
[4, 6]


Source:
http://wolfram.kriesing.de/blog/index.php/2008/javascript-remove-element-from-array
Resource:
http://www.w3schools.com/jsref/jsref_splice.asp
http://stackoverflow.com/questions/5767325/remove-specific-element-from-a-javascript-array

No comments: