How to insert an item into an array at a specific index

Explanation

 You have to use a function name as splice on the native array object if you want to insert an item into an array at a specific index.

arr.splice(index, 0, item); this will insert an item into arr at the specified index (deleting 0 items first, that is, it’s just an insert).

So here we will take an example, where we will create an array. And will also add an element to it into the index at number 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge

 

 

Also read, Differences between a HashMap and a Hashtable in Java?

Share this post

Leave a Reply

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