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
bang on the money, thanks, looking for a tutorial, found this, worked great, peace!
cool…
thanks for you’re code example.
exactly which I looked for 😉
björn(..)
fantastic document…
Thanks for the post. Helpful stuff.
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.
Thanks,
Works fine……..
thanks………….
It’s great!
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.
Great!
Thanks for the code…
This was very helpful !
Thanks.
a.splice(1,1); // Removes 1 element from index 1
Both those ‘1’s look the same to me…
splice(index, number of elements) in case anyone is wondering
Tom Van Schoor, your function is full of errors. i, what’s i? index, of course. Improve performance? 2 calls to indexOf, when you have the result in index variable.
Gigi, before do some critics like u….
do it better okay? 😉
I like that script… i did just put a ”return;” after splice
Thanks Billis for defending, commenting and breaking down is easy.
Some ppl think they have to copy paste stuff without thinking about it.
All i put was a suggestion out of my head.
Instead of breaking it down like that, rather improve the code so others can learn from it.
var i = this.indexOf(s);
if(this.indexOf(s) != -1)this.splice(i, 1);
}
error removed from my comment
oops again…
Array.prototype.remove=function(s){
var i = this.indexOf(s);
if(this.indexOf(s) != -1)this.splice(i, 1);
}
}
To make it all complete and tidy:
Array.prototype.remove=function(s){
var i = this.indexOf(s);
if(i != -1) this.splice(i, 1);
}
Gigi has a point, but it would have been better if this was ”his” contribution. No hard feelings though ^^
Works great!
I want to remove repeated values in the string. suppose the string is
123:234:123:234
values are repeating I want the output
as 123:234
great!
it was of great aid…