My initial, and extremely incorrect thought was that I could just use
to remove the element as such:
const testArray = ['one', 'two', 'three']; delete testArray;
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
deletes the value explicitly. When in the context of an array, that leaves you
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.
accomplished with the
splice method. It will edit the array in place, similar
to what I was trying to accomplish with the
const testArray = ['one', 'two', 'three']; testArray.splice(1, 1);
And the resulting array will be the more desirable:
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);
removedValue would then hold the following:
Not much to it! Hopefully next time this one comes up for me I won’t make the
mistake of using