Inserting an element in an array at a specific position in JavaScript

In this tutorial, we will understand how to insert an element at any index in an array in JavaScript.

Firstly, let us see about Arrays in JavaScript.

In JavaScript Arrays are heterogeneous in nature.

Creating an array:

const array = [“integer”“float”, “string”];

Here if an array is declared with const cannot be reassigned.

Insertion of elements in JavaScript array:

In array, it is not possible to insert the new element without replacing the existing element at the same position.

For example:

var arr = []; 
arr[0] = "apple";
arr[1] = "brinjal";
arr[2] = "vegetable";
arr[3] = "dell";
arr[4] = "laptop";
console.log(arr.join());
//if we insert a new element at position 1 then apple will be replaced by the new element.
arr[1]="friut";
console.log(arr.join());

output:

apple,brinjal,vegetable,dell,laptop
fruit,brinjal,vegetable,dell,laptop

So, inserting an element without replacing the element can be done using splice method.

splice method in JavaScript to insert an element in an array at a specific position in JavaScript

splice() method can add or remove array elements.

Syntax:

Splice can be used using different parameters.

Let us consider deleteCount=>n and start=>index.

splice(start, deleteCount) => it deletes n elements starting from the index. 
splice(start, deleteCount, item1) => it can be used to insert single element by specifying deleteCount=0


splice(start, deleteCount, item1, item2, itemN)=> it can be used to add many elements.

Let us see an example to insert an element at a specific position in an array.

Example:

var arr = []; 
arr[0] = "apple";
arr[1] = "brinjal";
arr[2] = "vegetable";
arr[3] = "dell";
arr[4] = "laptop";
console.log(arr.join());
arr.splice(1, 0, "fruit");
console.log(arr.join());

Output:

apple,brinjal,vegetable,dell,laptop
apple,fruit,brinjal,vegetable,dell,laptop

Explanation:

Here we have inserted an element at index 1 without replacing “brinjal”.

Here start=1 and deleteCount=0 and item=”fruit”.

Leave a Reply

Your email address will not be published. Required fields are marked *