Nov
14
Posted (Johan Känngård) in JavaScript on 2005-11-14

If you know the index of the element to remove, you could use the splice method, like this:

var a=['one','two','three','four'];
a.splice(1,1); // Removes 1 element from index 1
alert(a); // Results in 'one','three','four'


If you don’t know the index, but the value of the element, you could add a little method to the Array class like this:

Array.prototype.remove=function(s){
  for(i=0;i<this .length;i++){
    if(s==this[i]) this.splice(i, 1);
  }
}
var a=['one','two','three','four'];
a.remove('three');
alert(a); // Results in 'one','two','four'


Comments:
chris thomas on February 27th, 2006 at 11:49:36 #

bang on the money, thanks, looking for a tutorial, found this, worked great, peace!

björn kirchmeier on February 6th, 2007 at 22:10:59 #

cool…

thanks for you’re code example.

exactly which I looked for ;-)

björn(..)

jiten on May 22nd, 2007 at 11:52:57 #

fantastic document…

Christian Wyglendowski on June 20th, 2007 at 14:20:03 #

Thanks for the post. Helpful stuff.

Rodrigo DeJuana on January 28th, 2008 at 18:59:42 #

There is an error in this code. Splicing the array shortens the array. When the array removes the ‘three’ the i and length will be mismatched and it will skip the cell after the ‘three’. You need to decrement i– after the splice to keep them in sync.

Rasanka on February 1st, 2008 at 09:55:14 #

Thanks,

Works fine……..
thanks………….

springrider on February 20th, 2008 at 11:31:40 #

It’s great!

Tom Van Schoor on April 17th, 2008 at 21:51:32 #

I would suggest the following

Array.prototype.remove=function(s){
var index = this.indexOf(s);
if(this.indexOf(s) != -1)this.splice(i, 1);
}

it is same result without the for loop… although javascript interpreters probably loop the array aswel.

Jitendra Kumar Saini on May 7th, 2008 at 11:19:39 #

Great!
Thanks for the code…

Deo on May 16th, 2008 at 11:25:42 #

This was very helpful !
Thanks.

Post a comment
Name: 
Email: 
URL: 
Comments: