WEBDOOD.COM

Javascript Array.remove and Array.indexOf methods

by webdood on Jan.01, 2011, under Javascript, Software Development

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]
//    Presumably this will eventually be added to Javascript, but until that day...
////////////////////////////////////////////////////////////////////////////////
if (Array.prototype.remove===undefined) {
  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

:, ,

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org