How to add an item to an array at a specific index in JavaScript

Learn how to add items to an array at a specific index in JavaScript

Suppose you want to add items to the array, but you don't want to add items to the end of the array. You want to explicitly add it to a specific position in the array.

That place is calledindex.

Array index from0, So if you want to add items first, you can use index0, Followed by index1, and many more.

To do this, you will usesplice()Array method. This function is very powerful, in addition to the functions we are going to use now, it also allows deleting items from the array. Therefore, please proceed with caution.

splice()Accept 3 or more parameters. The first is to start indexing: where we will start making changes. The second is to delete the count parameter. YesplusArray, so in all our examples, the delete count is 0. After that, you can add one or more items to add to the array.

This is an example. Take this array:

const colors = ['yellow', 'red']

You can add an item lateryellowuse:

colors.splice(1, 0, 'blue')
//colors === ['yellow', 'blue', 'red']

You can add multiple items lateryellow, Use:

colors.splice(1, 0, 'blue', 'orange')
//colors === ['yellow', 'blue', 'orange', 'red']

Note: result assumptioncolorsstill is['yellow', 'red']

To add in the first position, use0As the first parameter:

colors.splice(0, 0, 'blue')
//colors === ['blue', 'yellow', 'red']

Download mine for freeJavaScript beginner's manual

More js tutorials: