How to insert an item into an array at a specific index (JavaScript)
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,Borgearr.splice(2, 0, "Lene");console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
You can implement the Array.insert
method by doing this:
Array.prototype.insert = function ( index, item ) { this.splice( index, 0, item );};
Then you can use it like:
var arr = [ 'A', 'B', 'D', 'E' ];arr.insert(2, 'C');// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
Other than splice, you can use this approach which will not mutate the original array, but it will create a new array with the added item. You should usually avoid mutation whenever possible. I'm using the ES6 spread operator here.
const items = [1, 2, 3, 4, 5]const insert = (arr, index, newItem) => [ // part of the array before the specified index ...arr.slice(0, index), // inserted item newItem, // part of the array after the specified index ...arr.slice(index)]const result = insert(items, 1, 10)console.log(result)// [1, 10, 2, 3, 4, 5]
This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well:
const items = [1, 2, 3, 4, 5]const insert = (arr, index, ...newItems) => [ // part of the array before the specified index ...arr.slice(0, index), // inserted items ...newItems, // part of the array after the specified index ...arr.slice(index)]const result = insert(items, 1, 10, 20)console.log(result)// [1, 10, 20, 2, 3, 4, 5]