Saturday, January 1, 2011

Array.remove method (also Array,indexOf

I kept finding myself needing to remove items from an array, so developed a quick helper (prototype) method attached to the Array Object to help.


////////////////////////////////////////////////////////////////////////////////
//
// Array.remove( object|string item) - removes an item from an array
// Example x = ["abc","xyz",1,4] x.remove("xyz") returns ["abc",1,4]
//
////////////////////////////////////////////////////////////////////////////////
if (Array.prototype.remove===undefined) { // Presumably this will eventually be added to Javascript
Array.prototype.remove = function( item ) {
var itemLocation = this.indexOf(item);
if (itemLocation > -1) {
this.splice(itemLocation,1);
}
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Array.indexOf() - returns integer index where valueToSearchFor is in an Array
// (believe it or not, not all browsers have this yet ... and it's 2010!
////////////////////////////////////////////////////////////////////////////////
if (Array.prototype.indexOf===undefined) {
Array.prototype.indexOf = function( valueToSearchFor ) {
var iEnd = this.length;
var retVal = -1;
for (var i=0;i<iEnd; i++) {
if (this[i] == valueToSearchFor) {
retVal = i;
break;
}
}
return retVal;
};
}


Shannon Norrell

1 comment:

WebDood said...

Awesome helper method! I am so glad I can google myself.