Anjan Dutta
Insert an item at a specific index of an array in Javascript
Insert an item at a specific index of an array in Javascript
Arrays are the most interesting non-primitive data type in Javascript. It comes with many internal functions. And if required, we can write custom functions to manipulate an array.
Today, I am going to describe how to insert an item at a specific index of an array in javascript.
We can insert an element mainly in three positions in an array.
- Insert at the beginning of an array.
- Insert at the end of an array.
- Or, insert at any position in an array.
Insert at the beginning of an array
To insert at the beginning of an array, we do not need to write any custom function. We are going to use a pre-defined method unshift()
.
The unshift()
method takes any number of comma-separated parameters. Ideally, all these parameters would be the items to be inserted at the beginning of an array.
Here is an example.
var number_list = ["Three", "Four", "Five"];number_list.unshift("One", "Two");
// ["One", "Two", "Three", "Four", "Five"]
Remember, the order of insertion will be same as we pass on the parameters.
Insert at the end of an array
Many of us probably know the solution. Yes, its easy one. Using a push()
function, we can insert any element at the end of an array.
The push()
function takes any number of parameters, and the order of insertion remains the same.
Here is an example.
var number_list = ["Three", "Four", "Five"];number_list.push("One", "Two");
// [ "Three", "Four", "Five", "One", "Two"]
Insert an item at a specific index of an array in Javascript
To solve this problem, we are going to use the splice()
method in javascript.
The splice()
method takes three to n number of parameters.
First is the position or index where we want to insert the item.
Second is the number of elements we would like to remove. Here, we are trying to inject an element. So, the parameter will be 0.
The third parameter is the n number of comma-separated elements we will insert into the array.
Here is an example.
var number_list = ["Three", "Four", "Five"];number_list.splice(1, 0, "One", "Two");console.log(number_list);
// ["Three", "One", "Two", "Four", "Five"]```
See in the above example, "One" and "Two" has been inserted respectively.
export const _frontmatter = {"title":"Insert an item at a specific index of an array in Javascript","description":"Insert an item at a specific index of an array in javascript. unshift, push, splice methods explained here to insert in the beginning and end of an array.","image":"/banner.jpeg","lastModified":"","disableTableOfContents":false}