Recently I was faced with the need to remove an item from an array, by index in JavaScript and I came to realize it had been quite a while since I had to do something like that.

My initial, and extremely incorrect thought was that I could just use delete to remove the element as such:

const testArray = ['one', 'two', 'three'];
delete testArray[1];

Since this data was being used to render rows in a table, “deleting” the value didn’t actually update the table as expected. That’s because using delete it deletes the value explicitly. When in the context of an array, that leaves you with an undefined value at the index of the array.

The aforementioned deletion would leave you with this:

["one", undefined, "three"]

Oh so close.

Sadly, not even the first time I’ve made this mistake. Hence this post, as I figured the best way to commit this one to memory would be to write about it.

To remove an element (or elements) from a JavaScript array by index is accomplished with the splice method. It will edit the array in place, similar to what I was trying to accomplish with the delete command:

const testArray = ['one', 'two', 'three'];
testArray.splice(1, 1);

And the resulting array will be the more desirable:

["one", "three"]

The first argument of the splice command is the index of the element we want to delete. The second argument tells splice to delete 1 element. If you were to omit the second argument, splice would remove the rest of the array, starting at the index in the first argument.

An added bonus to using the splice method is that it will return the element values (as an array) that are deleted, so if you wanted to not only remove the value, but do something additional with it, you could:

const testArray = ['one', 'two', 'three'];
const removedValue = testArray.splice(1, 1);

The removedValue would then hold the following:

["two"]

Not much to it! Hopefully next time this one comes up for me I won’t make the mistake of using delete again!





Did you enjoy this post?

Cool if I slip into your inbox with more?
Full posts, 1-2 times per week: