The function above will remove the element at index
3. See docs.
Let’s say we have a simple array of strings, like this one:
We just want to remove that
‘bar’ element. How can we do this?
For the principle of least surprise, you could expect
Array to have a
The good news? We can create it!
But, first of all, let’s see how this is done in the standard way:
What does this
splice function do? Simple: it just removes the element at index
1. The first parameter is, indeed, the index, and the second is the number of elements to remove, starting from that index. This is all you need to know about
splice. If you’re curious to see what other cool things
splice can do, see the MDN documentation.
But what if I don’t know the index?
Oh well, you can get it. Just use
indexOf, this way:
Please note that Internet Explorer 8 and below versions don’t support it (you can use a polyfill, though).
Extending the Array object
This is the function I finally came up with.
I know some folks out there don’t feel comfortable with extending
Array, because they say Bad Things™ could happen. However, I think that a
remove function is just a lot more easy to use and remember than
splice, and honestly I don’t see any drawbacks with this approach; especially if we protect the global
Array object, somehow. What do you think?
Full example (from the browser’s console, as usual):
Awesome! But… why can’t I just use the
And it will Just Work™. By the way it has a flaw: it doesn’t simply remove that element from the array, but it actually replaces it with
Leaving place for undesirable things, like:
In conclusion, if you don’t care about the drawbacks, you can use the
delete keyword; otherwise go with the solution explained above.