insert item at index into js array

How to Insert Item into Array at Specific Index in JavaScript

JavaScript allows you to store data in arrays and perform various data manipulations on it. Each JS array comes with many out of the box functions such as push(), pop() that allows you to easily modify them. But sometimes you may need to insert an item into array at specific index in JavaScript. In this article, we will learn how to do it.


How to Insert Item into Array at Specific Index in JavaScript

Every JavaScript array supports splice() function that allows you to splice the array. splice() allows you to add/remove items and overwrite original array. So we will use this method to insert item at specific index in JS array. Here is its syntax.

array.splice(index, howmany, item1, ....., itemX)

index - (Required) The position to add/remove items.
 Negative value defines the position from the end of the array.
howmany	- (Optional) Number of items to be removed.
item1, ..., itemX - (Optional) New elements(s) to be added.

Let us say you have the following array in JavaScript.

arr = ['a','b','c','d','e'];

Let us say you want to insert ‘g’ after number ‘b’ in the above array. Here is the command to do it.

console.log(arr.join()); // a,b,c,d,e
arr.splice(2, 0, "g");
console.log(arr.join()); // a,b,g,c,d,e

In the above splice() command, we mention the first argument as 2 for the index where we want to insert item. We mention the next item as 0 since we don’t want to remove any item from the array. We mention the 3rd argument as ‘g’, the item that we want to insert.

It also works on array of numerical and even mixed data types. Here is an example to insert 100 in an array consisting of numerical items.

arr = [10,20,30,40,50];
console.log(arr.join()); // 10,20,30,40,50
arr.splice(2, 0, "100");
console.log(arr.join()); // 10,20,100,30,40,50

Here is an example to insert element ‘jim’ in an array of item of mixed data type.

arr = [10,'a',30,'b',50];
console.log(arr.join()); // 10,a,30,b,50
arr.splice(2, 0, "jim");
console.log(arr.join()); // 10,a,100,30,b,50

You can also create a method to readily call it on all JS arrays, as shown below.

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

It is basically the same splice() function we used earlier, but encapsulated inside a function definition. Once your define the method, you can call it as shown below.

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');  
console.log(arr); // [ 'A', 'B', 'C', 'D', 'E' ]

In this article, we have learnt how to insert item into array at specific index in JavaScript.

Also read:

How to Find Files Larger Than 100Mb in Linux
How to Undo & Redo in Nano Editor
How to Undo & Redo in Vim/Vi Editor
How to Set Timeout in cURL
How to Set Indentation in Vim Editor

Leave a Reply

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