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.

  1. Insert at the beginning of an array.
  2. Insert at the end of an array.
  3. 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. 

Look at the example below:

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. 

See the syntax below:

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.

See the code below:

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.

Leave a Comment

− three = one