How to Add Item to Array at Specific Index in JavaScript

Updated onbyAlan Morel
How to Add Item to Array at Specific Index in JavaScript

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?

In this post, we'll learn how to add an item to a specific index you want in the array in JavaScript.

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

First, let's start with our example element and array:

JAVASCRIPT
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.

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:

JAVASCRIPT
array.splice(3, 0, element);

Now let's look at the full code example:

JAVASCRIPT
const element = "element"; const array = ["a", "b", "c", "d", "e"]; const index = 3; array.splice(index, 0, element); console.log(array);
BASH
["a", "b", "c", "element", "d", "e"]

Conclusion

In this post, we learned how to add an item to a specific index in an array in JavaScript.

Simply use the splice method and pass it additional arguments to add your element in the index you specified.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.