How to Add an Item to an Array at a Specific Index in JavaScript
Learn how to add an item to an array at a specific index in JavaScript.
If you want to add an item to an array at a specific position instead of appending it at the end, you can do so by specifying the index where you want to add the item.
Note: Array indexes start from
0
. So, to add an item at the beginning of the array, you would use index0
. For the second position, the index is1
, and so on.
To accomplish this task, you can use the splice()
method of an array. The splice()
method is powerful and can be used not only to add items but also to delete them. Therefore, use it with caution.
The splice()
method accepts 3 or more arguments. The first argument is the start index, which indicates the position where the changes will take place. The second argument is the delete count parameter, which is 0 for all our examples since we are adding items. After that, you can specify one or multiple items to be added to the array.
Here’s an example:
1 | const colors = ['yellow', 'red']; |
To add an item after “yellow”, you can use the following code:
1 | colors.splice(1, 0, 'blue'); |
To add multiple items after “yellow”, you can use the following code:
1 | colors.splice(1, 0, 'blue', 'orange'); |
Note: The result assumes that
colors
is still['yellow', 'red']
.
To add an item at the first position, you can use 0
as the first argument:
1 | colors.splice(0, 0, 'blue'); |
tags: [“JavaScript”, “array manipulation”, “splice method”, “add item at specific index”]