How to remove a specific value from a javascript array

Posted September 30, 2009 by Brian Cray

Reading time: About 1 minute

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;
  };
}

About the author

Photo of Brian Cray

Brian Cray is a Columbus, Ohio-based web entrepreneur & consultant. View some of Brian’s work in his portfolio and learn how to make kick ass websites by reading his blog.

14 Article comments

Show/add comments

0 Article references from other blogs

Show all references

1311
Previous:
Next: