When you are working with an array and want to add an element, it is easy to add it to the start and end of an array, there are built-in functions for that.
However, what if you want to add an element to a specific index in an array?
How to add an item to a specific index in an array
First, let's start with our example element and array:
const element = "element"; const array = ["a", "b", "c", "d", "e"];
Now let's say you want to add it to the 3rd index of the array. You can do that by using the
splice method can take 3 arguments, the first one is the index you want to start from, the second one is the number of elements you want to remove, and the third one is the element you want to add.
We want to start at the 3rd index so we can pass
3 as the first argument.
We don't want to delete anything, so we can pass
0 as the second argument.
And we want to add our element, so we can pass
element as the third argument.
As a result, our usage of the
splice method will look like this:
array.splice(3, 0, element);
Now let's look at the full code example:
const element = "element"; const array = ["a", "b", "c", "d", "e"]; const index = 3; array.splice(index, 0, element); console.log(array);
["a", "b", "c", "element", "d", "e"]
Simply use the
splice method and pass it additional arguments to add your element in the index you specified.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!