To insert an item or element to a specific index in an array, you can use the splice()
array method in JavaScript.
Most of the time we may be using the splice()
method to remove an item from a specific position in an array. To know more about it, check out Removing items from an array using the splice()
method →.
Consider this array of names,
// names array
const namesArr = ["Jon", "Roy", "Riya"];
Let's say we need to need to insert the name Rony
at index position 1
after Jon's
name.
We can do that with the help of the splice()
method by passing 3
arguments to the method:
- The first argument is the
index
position you want the item to be inserted. - The second argument being the number of elements to be deleted starting from the index position, in our case we don't want anything to be deleted so we will pass
0
as the second argument. - And the third argument is the item, in our case
Rony
.
So let's code that in JavaScript,
// names array
const namesArr = ["Jon", "Roy", "Riya"];
// name to add
const nameToAdd = "Rony";
/*
Using the splice() array method
to add an item at index position 1 🌟
Argument 1: The index position to add item
Argument 2: No. of items to delete starting from the index position,
In our case 0 items to delete
Argument 3: The item to add
*/
namesArr.splice(1, 0, nameToAdd);
console.log(namesArr); // ["Jon", "Rony", "Roy", "Riya"]
Yes!! We have successfully inserted our item Rony
at index position 1
🌟.
See this example live in JSBin.