We can easily insert items at the start (unshift
) and end (push
) of an array.
But, what about the middle? ๐ค
Ta-da! splice
!
splice
is a method that allows you to insert and delete items in an array.
It takes three arguments:
The index you want to start your operation
The number of items you wish to delete (optional)
The list of items you wish to insert (optional)
Let's go over some examples.
Inserting a Single Item
Let's correct the array we showed at the beginning.
const array = ['a', 'b', 'c', 'e', 'f', 'g'];
array.splice(3, 0, 'd');
console.log(array)
So, what happens is this:
We walk to index
3
, which is pointing to the elemente
We delete
0
itemsThen we insert
d
at index3
, effectively shiftinge
Inserting Multiple items
const array = ['a', 'b', 'c', 'd', 'h', 'i', 'j', 'k'];
array.splice(4, 0, 'e', 'f', 'g');
console.log(array)
So, a breakdown of what happens is:
We walk to index
4
, which is pointing to the elementh
We delete
0
items (again)Then we insert
e
,f
andg
at index4
(putting them in the correct place)
Bonus: Inserting and Deleting
Now, you might be wondering... (or not)
How does the delete part work?
const array = ['Apple', 'Banana', 'Orange', 'Mandarin', 'Blueberry'];
array.splice(2, 2, 'Raspberry');
console.log(array)
It's similar to what happened before:
We walk to index
2
, which is pointing to the elementOrange
We delete
2
items (Orange
andMandarin
)Then we insert
Raspberry
at index2
Bonus: Bonus
An interesting behavior happens if you omit the number of items to delete.
const array = ['a', 'b', 'c', 'd', 'h', 'i', 'j', 'k'];
array.splice(1);
console.log(array)
Here's what happens:
We walk to index
1
, which is pointing to the elementb
We delete all items from that point onwards
Then we insert nothing
Leaving us with just one element.
From mdn:
If
deleteCount
is omitted, or if its value is greater than or equal to the number of elements after the position specified bystart
, then all the elements fromstart
to the end of the array will be deleted.
splice
is a pretty interesting and versatile method.
What applications have you found for it?
Thanks for reading. ๐.