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.
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays.sort(arr) method.
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With