Remove a specific element from an array in JavaScript?
I have an array of integers, which I'm using the .push()
method to add to.
Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int);
I have to use core JavaScript - no frameworks are allowed.
Array
Javascript
- asked 9 years ago
- B Butts
2Answer
First, find the index
of the element you want to remove:
var array = [2, 5, 9];
var index = array.indexOf(5);
Note: browser support for indexOf is limited; it is not supported in Internet Explorer 7 and 8.
Then remove it with splice
:
if (index > -1) {
array.splice(index, 1);
}
The second parameter of splice
is the number of elements to remove. Note that splice
modifies the array in place and returns a new array containing the elements that have been removed.
- answered 8 years ago
- Sandy Hook
I don't know how you are expecting array.remove(int)
to behave. There are three possibilities I can think of that you might be wanting.
To remove an element of an array at an index i
:
array.splice(i, 1);
If you want to remove every element with value number
from the array:
for(var i = array.length - 1; i >= 0; i--) {
if(array[i] === number) {
array.splice(i, 1);
}
}
If you just want to make the element at index i
no longer exist, but you don't want the indexes of the other elements to change:
delete array[i];
- answered 8 years ago
- Sunny Solu
Your Answer