Borislav Hadzhiev
Mon Oct 11 2021·3 min read
Photo by Christopher Machicoane
Use the splice()
method to add an element into an array at a specific index.
The method changes the contents of an array by removing, replacing or adding new
elements, starting at a supplied index.
const arr = ['a', 'c']; arr.splice(1, 0, 'b'); // 👇️ ['a', 'b', 'c'] console.log(arr);
The parameters we pass to the Array.splice method are:
0
and the last an index of arr.length - 1
.What might seem confusing to you is:
"Why are we providing a delete count parameter when adding an element to the array?".
The splice
method is used to do 3 very different things.
Here's the same example, using named variables to make this a little more readable.
const arr = ['a', 'c']; const startIndex = 1; const deleteCount = 0; const elementToInsert = 'b'; arr.splice(startIndex, deleteCount, elementToInsert); // 👇️ ['a', 'b', 'c'] console.log(arr);
We start changing the array at index 1
, delete 0
elements and add an element
with the value of b
at the start index (1
).
splice
method returns an array containing the deleted elements, however because we set the second parameter (delete count) to 0
it would return an empty array.We can also insert more than 1 element, starting at the supplied index.
const arr = ['a']; arr.splice(1, 0, 'b', 'c'); // 👇️ ['a', 'b', 'c'] console.log(arr);
In this example we add the elements with values b
and c
in the array,
starting at index 1
.
The elements will be added in the order they were provided to the splice
method, meaning b
will be at index 1
and c
will be at index 2
.
If you have an array containing the elements you want to add starting at the specified index, you can use the spread operator (...).
const arr = ['a']; const elements = ['b', 'c']; arr.splice(1, 0, ...elements); // 👇️ ['a', 'b', 'c'] console.log(arr);
An easy way to think about the
spread operator (...)
is that we are unpacking the values from the array and passing them as multiple
comma-separated arguments to the splice
method.
I couldn't tell you why they thought it would be a good idea to use the same method to replace, remove and add elements to an array.
splice
method it takes you a couple of seconds to remember the order of the parameters and to determine how it is used. Are we adding / removing or replacing elements here.