Remove specific item from a javascript array that matches a passed string

September 1st, 2008 by Nikhil

Here’s quick way of extending the native Javascript Array Object, just to do that…

Array.prototype.removeItem=function(str) {
   for(i=0; i<this.length ; i++){
     if(escape(this[i]).match(escape(str.trim()))){
       this.splice(i, 1);  break;
     }
   }
  return this;
}

So now you can do something like this…

var animals= new Array("dog","lion","cat","tiger","elephant");
animals.removeItem('tiger');

Now the animals array will contain “dog”,”lion”,”cat”,”elephant”;

 PS: And here is the String Trim Prototype too …

String.prototype.trim=function(str) {
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

 
Enjoy….

Tags: , ,


get ExpressingIT News by Email Subscribe to ExpressingIT by Email |  Follow Me on Twitter


2 Responses to “Remove specific item from a javascript array that matches a passed string”

  1. Round Kitchen Says:

    -.- I am very thankful to this topic because it really gives up to date information ;’.


  2. Dwayne Says:

    A VERY useful function. Although I didn’t spend much time working out how, I wanted to remove a whole bunch of elements from an array, but instead just had multiple calls to the .removeItem function instead.


Leave a Reply

 Subscribe to ExpressingIT RSS
get ExpressingIT News by Email Subscribe to ExpressingIT by Email
 Follow Me on Twitter