Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to remove item from array by value?

Is there a strategy to eliminate an item from a JavaScript array?

Given an array:
var ary = ['three', 'seven', 'eleven'];


I might want to accomplish something like:
removeItem('seven', ary);


I've investigated splice() yet that solitary eliminates by the position number, though I need something to eliminate an item by its value.
by

2 Answers

akshay1995
You can use the indexOf method like this:

var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
kshitijrana14
This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};

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

ary.remove('seven');

/ returned value: (Array)
three,eleven
*/


To make it a global-

function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/* returned value: (Array)
three,eleven
/


And to take care of IE8 and below-

if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(what, i) {
i = i || 0;
var L = this.length;
while (i < L) {
if(this[i] === what) return i;
++i;
}
return -1;
};
}

Login / Signup to Answer the Question.