How to insert an item into an array at a specific index in JavaScript

October 12, 2022 No comments javascript arrays tips solutions

Introduction

Sometimes, we may wish to insert an item into an array at a specific index in JavaScript. In this post, we'll learn how to do it.

How to insert an item into an array at a specific index in JavaScript

To insert an item into an array at a specific index in JavaScript you need to use the splice() function.

In the following example, we will create an array and add elements to it. Then we will use splice(2, 0, "CCCCCCCC") function to insert element on index 2 with value "CCCCCCCC":

var array = [];
array[0] = "a";
array[1] = "b";
array[2] = "c";
array[3] = "d";
array[4] = "e";

console.log(array); // [a,b,c,d,e]

array.splice(2, 0, "CCCCCCCC");
console.log(array); // [a,b,CCCCCCCC,c,d,e]

Conclusion

In this short article, we described how to insert an item into an array at a specific index in JavaScript.

{{ message }}

{{ 'Comments are closed.' | trans }}