Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an item into an array at a specific index (JavaScript)

I am looking for a JavaScript array insert method, in the style of:

arr.insert(index, item) 

Preferably in jQuery, but any JavaScript implementation will do at this point.

like image 463
tags2k Avatar asked Feb 25 '09 14:02

tags2k


People also ask

How do I push an item to the first index of an array?

The unshift() method adds new elements to the beginning of an array. The unshift() method overwrites the original array.

How do you add an element to an array in JavaScript?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.

How to insert element/item into an array at a specific index?

In this tutorial, we are going to learn about how to insert element/item into an array at a sepcific index in JavaScript. JavaScript gives us a splice ( ) method by using that we can add new elements into an array at a specific index. The splice (index,numberofItemstoRemove,item) method takes three arguments which are

How do I add elements to an array in JavaScript?

In this article, we looked at many ways in JavaScript we can add elements to an array. We can add them to the beginning with unshift (). We can add them to the end using their index, the pop () method and the concat () method. We get even more control of where we place them with the splice () method.

How to array Array at specific index in JavaScript?

array at specific index in JavaScript? The for loop can be used to move all the elements from the index (where the new element is to be inserted) to the end of the array, one place after from their current place. The required element can then be placed at the index.

How to add or remove items from an array in JavaScript?

The array.splice () array method is used to add or remove items from array taking three arguments: the index where the element id should be inserted or removed, the number of items that should be deleted, and the new items that should be inserted. The insertion will be setting the number of elements to be deleted to 0.


1 Answers

You want the splice function on the native array object.

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

In this example we will create an array and add an element to it into index 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
like image 158
tvanfosson Avatar answered Sep 22 '22 10:09

tvanfosson