I have an array of numbers and I'm using the .push()
method to add elements to it.
Is there a simple way to remove a specific element from an array?
I'm looking for the equivalent of something like:
array.remove(number);
I have to use core JavaScript. Frameworks are not allowed.
Best Answer
Find the
index
of the array element you want to remove usingindexOf
, and then remove that index withsplice
.The second parameter of
splice
is the number of elements to remove. Note thatsplice
modifies the array in place and returns a new array containing the elements that have been removed.For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of
5
from[2,5,9,1,5,8,5]
), while the second function removes all occurrences:In TypeScript, these functions can stay type-safe with a type parameter: