HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can I insert an item into an array at a specific index?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
insertarrayindexhowcanspecificiteminto

Problem

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

arr.insert(index, item)


It should preferably be in jQuery, but any JavaScript implementation will do at this point.

Solution

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




UPDATE (24 May 2024)

You can now use the toSpliced method which behaves just like splice, however it returns a new array without mutating the existing one.

You could update the previous example like so:
const updated = arr.toSpliced(2, 0, "Lene");

Context

Stack Overflow Q#586182, score: 6875

Revisions (0)

No revisions yet.