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)
Answer from SLaks on Stack OverflowWhy is removing a specific element from an array so needlessly complicated in Javascript?
How do I remove from an array those elements that exists in another array?
Is it possible to remove individual values from an file input multiple element?
Overwrite array in object array by value of a key?
Videos
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)
A one-liner will do it,
var arr = ['three', 'seven', 'eleven'];
// Remove item 'seven' from array
var filteredArray = arr.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]
// In ECMA6 (arrow function syntax):
var filteredArray = arr.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).
I'm just looking for something along the lines of:
array.remove("element")Upon Googling for solutions so far I've found
Remove an element at any index with splice
Remove an element from an array with a for loop and push
Remove an element at any position of an array with slice and concat
There's more but I'm assuming you get the point. Why is this seemingly simple task so ridiculously complicated with Javascript?
Did nobody think to include a ".remove()" method when they were first developing Javascript? Is there a quirk of the language that makes it impossible? What is the reason for this?