Inserts an element at a specified location at a specific index of the JS array
- 2020-03-30 03:35:23
- OfStack
Many array-related tasks sound simple, but that's not always the case, and developers often don't use them. I recently encountered a requirement to insert an element into a specific index of an existing array. It sounds easy and common, but it takes a little time to study it.
//The original array
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
//Splicing function (index position, number of elements to delete, element)
array.splice(2, 0, "three");
array; // Now the array looks like this ["one", "two", "three", "four"]
If you're comfortable with extending native JavaScript, you can add this method to an Array prototype:
Array.prototype.insert = function (index, item) {
this.splice(index, 0, item);
};
At this point, you can call:
var nums = ["one", "two", "four"];
nums.insert(2, 'three'); //Note the array index, [0,1,2..]
array // ["one", "two", "three", "four"]