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

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….


Leave a Reply

 
NDK home | Expressing IT | Expressing Palate | Expressing Penmenship | Expressing Awe | Expressing Myself