How to remove a specific value from a javascript array

I couldn’t find a short and sweet answer to this one, so I made an answer and I’m sharing it here if you need it. Enjoy!

// from this
var arr = ['remove', 'specific', 'value', 'from', 'javascript', 'array']; // 6 items
 
// to this ("specific" value removed)
var arr = ['remove', 'value', 'from', 'javascript', 'array']; //  5 items
 
// use this (removes "specific")
arr.splice(arr.indexOf('specific'), 1);
 
 
// full example
var arr = ['remove', 'specific', 'value', 'from', 'javascript', 'array'];
var value_to_remove = 'specific';
arr.splice(arr.indexOf(value_to_remove), 1);
 
 
// note: to support IE (anger rising as I type), you'll need this (thanks James!):
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;
 
    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;
 
    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

Published September 30, 2009. Tagged: . Read it later with Instapaper

All original content is © Brian Cray. I reserve all rights unless otherwise stated. Request permission to reuse content through Twitter