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 Solution
Find the
indexof the array element you want to remove usingindexOf, and then remove that index withsplice.The second parameter of
spliceis the number of elements to remove. Note thatsplicemodifies 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
5from[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: