The array methods are confusing sometimes if you don’t know which method is suitable for your situation. This article explains how to insert an element to a specific index in an array.
Inserting Element to a Specific Index in Array
You can use the splice
method to insert an element to a specific index in an array. The splice method is used for multiple purposes and one of them is to insert an element in an array. The following example inserts a new number at 3rd index.
1 2 3 4 5 6 7 8 9 10 11 |
const numbers = [2,34,5,64,67,90] const newArray = numbers.splice(3,0, 21) console.log(newArray) // [] console.log(numbers) // [2, 34, 5, 21, 64, 67, 90] |
The splice
method takes 3 arguments. The first argument is the index where you want to insert the new element. The second argument is the number of elements you want to remove from the array. The third and final argument is the actual element you want to insert.
Inserting a New Element in Place of an Old Element
You can remove an element with splice
method and insert a new element on the same index. The following example inserts a new element in place of an old element.
1 2 3 4 5 6 7 8 9 10 11 |
const numbers = [2,34,5,64,67,90] const newArray = numbers.splice(2,1, 21) console.log(newArray) // [5] console.log(numbers) // [2, 34, 21, 64, 67, 90] |
The above example removes 5
from the array and returns in newArray
. At the same time, it also inserts a new element and modifies the original array. The first argument is the index where the new element will be inserted, the second specifies the number of elements you want to remove from the array. The third argument is the element you want to insert into the array.
How to Insert Multiple Elements After an Index
You can also use splice
method to insert multiple elements into the array after a specific index. The following example adds 3 new elements at 2nd index in the array without removing anything.
1 2 3 4 5 6 7 8 9 10 11 |
const numbers = [2,34,5,64,67,90] const newArray = numbers.splice(2,0, 21, 22,23) console.log(newArray) // [] console.log(numbers) // [2, 34, 21, 22, 23, 5, 64, 67, 90] |
You can specify as many arguments as you want after 2nd argument. The elements you specify are added into the array.
Conclusion
You can use splice
method to insert an element to a specific index in an array. The splice
method can be used for multiple purposes, you can also remove elements and insert new elements at the same time. Read more about splice
the method on Mozilla documentation. If you are confused about using slice
and splice
when working with arrays, please read slice vs splice for more understanding.