How to remove item from array by value?

MacMac picture MacMac · Oct 17, 2010 · Viewed 1.2M times · Source

Is there a method to remove an item from a JavaScript array?

Given an array:

var ary = ['three', 'seven', 'eleven'];

I would like to do something like:

removeItem('seven', ary);

I've looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.

Answer

SLaks picture SLaks · Oct 17, 2010

You can use the indexOf method like this:

var index = array.indexOf(item);
if (index !== -1) {
  array.splice(index, 1);
}

Note: You'll need to shim it for IE8 and below

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
array.splice(index, 1);

console.log(array)