In JavaScript, and just like many other languages out there, at some point you'll likely need to remove an element from an array. Depending on your use-case this could be as easy as using the built-in shift()
or pop()
commands, but that only works if the element is at the beginning or end of the array, respectively. Many use-cases will require you to support removing an element from an arbitrary location in the array, which is what we'll cover here.
I'll also be explaining how to achieve this in other ways, like with the use of utility libraries that will handle it for you, or if you have to support older browsers like IE 8.
Vanilla JavaScript
To remove a particular element from an array in JavaScript we'll want to first find the location of the element and then remove it.
Finding the location by value can be done with the indexOf()
method, which returns the index for the first occurrence of the given value, or -1 if it is not in the array.
Using this index value we will then want to actually remove the element, which we can do with the splice()
method.
function removeElement(array, elem) {
var index = array.indexOf(elem);
if (index > -1) {
array.splice(index, 1);
}
}
So if indexOf
and splice
are the only two methods we need to achieve this, then what is the if-statement for? By checking if the index is greater than -1, we are verifying that the element is actually present in the array. If it wasn't, and index
is -1, then using this value in splice
will actually remove the last element in the array, which is not what we want.
Keep in mind that this only removes the first occurrence of the given element. See the following example to illustrate this:
var arr = [1, 2, 3, 3, 4, 5];
removeElement(arr, 3);
console.log(arr);
// Output:
// [ 1, 2, 3, 4, 5 ]
Notice that the second '3' is still present.
If we want to remove every instance of the specified element, then we can achieve this with a while-loop instead of the if-statement:
function removeAllElements(array, elem) {
var index = array.indexOf(elem);
while (index > -1) {
array.splice(index, 1);
index = array.indexOf(elem);
}
}
Now running the same example code as above, we get the following:
var arr = [1, 2, 3, 3, 4, 5];
removeAllElements(arr, 3);
console.log(arr);
// Output:
// [ 1, 2, 4, 5 ]
As you can see, both of the '3' elements are now removed from the array.
Libraries
With this being such a common use-case, most (if not all) of the utility libraries have a function to remove elements from an array.
Lodash
To remove an element, Lodash has the remove()
method. If you have a pretty simple use-case you're just wanting to remove a primitive element (like a number), then this function is probably overkill for you since you need to pass a function that determines if the element matches your criteria.
So, for example, here is how you'd remove the number 3:
var arr = [1, 2, 3, 3, 4, 5];
_.remove(arr, function(e) {
return e === 3;
});
console.log(arr);
// Output:
// [ 1, 2, 4, 5 ]
Notice that it has removed all instances of 3, which is the default behavior.
However, this method is more useful when removing more complex elements, like objects. For example, maybe you want to remove all "people" objects from an array if they are under 21 years old:
var people = [
{name: 'Billy', age: 22},
{name: 'Sally', age: 19},
{name: 'Timmy', age: 29},
{name: 'Tammy', age: 15}
];
_.remove(people, function(e) {
return e.age < 21
});
console.log(people);
// Output
// [ { name: 'Billy', age: 22 }, { name: 'Timmy', age: 29 } ]
It works a bit like the filter
method, except that it removes the elements from the array you pass and then returns an array of the removed elements from the method itself.
Underscore
The Underscore utility library has a similar method as Lodash, called reject
. It works very similarly, except for one notable difference. The resulting array is returned from the method, and the array you pass to it remains unchanged.
See the following code for an example:
var arr = [1, 2, 3, 3, 4, 5];
var ret = _.reject(arr, function(e) {
return e === 3;
});
console.log(arr);
console.log(ret);
// Output:
// [ 1, 2, 3, 3, 4, 5 ]
// [ 1, 2, 4, 5 ]
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Again, just like Lodash's remove
method, the reject
method is best suited for more complex cases, like removing objects or groups of elements.
Supporting Internet Explorer
If your project requires you to support old versions of Internet Explorer, specifically IE 8 in this case, then the indexOf()
method will not work for you since it isn't supported in this version of IE.
To deal with this, one solution is to shim the method, as shown in this Stack Overflow answer:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
According to the SO post, this is the implementation of indexOf
from MDN, used in Firefox/SpiderMonkey.
Another option would be to use jQuery
's $.inArray()
method:
var arr = [1, 2, 3, 3, 4, 5];
var idx = $.inArray(3, arr);
console.log(idx);
// Output:
// 2
This is roughly equivalent to indexOf
, which can then be used to write the removeElement
method as shown in the first section of this article.