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

📋 Table Of Content
In this article we will see how to insert an item into an array at a specific index in JavaScript.
In JavaScript, whenever we add an item in an array, it usually appends at the end of the array. But If you want to add the item anywhere at the middle of the array, you have to first specify the index
at which you want the item to be added.
However, there is no in-built methods in JavaScript which will directly allow us to insert an item or an element in an array at a specific index.
To solve this we can go head with approaches using splice()
method.
Using array.splice()
The splice()
is a very powerful JavaScript method that let us to add and remove or replace existing element from an array. The splice()
method overwrites the original array.
Syntax:
splice(start, deleteCount, item1)
start
: The index at which the content will change
deleteCount
: It mean the number of elements that will be removed from the start index. If it is 0 (zero) or negative, it means no elements will be removed.
item1
: The element that will be added in the array.
Lets check it with an example.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months)
OUTPUT:
["Jan", "Feb", "March", "April", "June"]
Here we have added 'Feb' in index 1 in the array.
Note: In Array the
index
start from0
.
Related Topics:
How To Remove A Specific Item From An Array In JavaScript ?
3 ways to loop an array in JavaScript | Quick ways
How to convert an array to object in javascript?
Check if an array includes a value/element in javascript.