It is that time of the week for Obvious Javascript Tip of the week. You probably already know how to delete an item from an array, maybe not. Sometimes it can be confusing, do I use the delete
keyword, do I use slice
or do I use splice
?
Splice of life
Using splice we can remove items from an array by providing the index (with the first item being zero).
// apple = 0, orange = 1, pineapple = 2, banana = 3
var myArr = ['apple', 'orange', 'pineapple', 'banana'];
myArr.splice(1, 1);
The above example will remove orange from our array (even though oranges are delicious) and the rest of the items will shift and have their indexes adjusted. The first argument is the starting index and the second argument is the number of items to remove.
So we could specify 2 for the second argument and remove both orange and pineapple, but we like pineapple too much to do that. You can also specify one or more optional parameters of items to replace the items removed from the third parameter onwards.
But, I don’t know the index…
Say hello to my little friend indexOf
which will let us search the array and return the index if it finds anything. Say you knew banana was in your array, but you didn’t know the index (maybe it just shuffled).
// apple = 0, orange = 1, pineapple = 2, banana = 3
var myArr = ['apple', 'orange', 'pineapple', 'banana'];
var banana = myArr.indexOf('banana');
if (banana != -1) {
myArr.splice(banana, 1);
}
You know, having said all of that, it might be worthwhile looking into using a Map
or Set
if you plan on adding and removing a lot of items, as splice can get pretty expensive for large arrays in my experience.
myArr.splice();
Thanks for sharing Dwayne! This is a great explanation of removing elements from an array using Splice() or the indexOf method.