EN
JavaScript - insert item into array at specific index
0 points
In this article, we would like to show you how to insert item into array at specific index using JavaScript.
Quick solution:
xxxxxxxxxx
1
var array = ['a', 'b', 'd'];
2
var index = 2;
3
var item = 'c';
4
5
array.splice(index, 0, item); // insert item at index (removing 0 items)
6
7
console.log(array); // [ 'a', 'b', 'c', 'd' ]
Note:
The second argument -
0
is the number of items to delete while inserting theitem
.
In this example, we extend the Array object by adding custom insert()
method that accepts 2 arguments: index
at which we want to insert the item, and the item
.
xxxxxxxxxx
1
Array.prototype.insert = function(index, item) {
2
this.splice(index, 0, item);
3
};
4
5
var array = ['a', 'b', 'd'];
6
7
array.insert(2, 'c');
8
9
console.log(array); // [ 'a', 'b', 'c', 'd' ]