How to remove item from array by value?
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.
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;
};
}
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);
if (index !== -1) array.splice(index, 1);
console.log(array)
A one-liner will do it,
var ary = ['three', 'seven', 'eleven'];
// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]
// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')
This makes use of the filter function in JS. It's supported in IE9 and up.
What it does (from the doc link)
filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.
So basically, this is the same as all the other for (var key in ary) { ... }
solutions, except that the for in
construct is supported as of IE6.
Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in
construct (AFAIK).
上一篇: 从JS数组中删除重复的值
下一篇: 如何通过值从数组中删除项目?