How to Insert an Item into an Array at a Specific Index
In this snippet, we are going to discuss a question concerning JavaScript array. Today’s topic covers the insertion of an item into the existing array at a specific index. However, there is no inbuilt method that directly allows inserting an element at any arbitrary index of the array.
One of the methods is the splice function. 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.
function insertAt(array, index, ...elementsArray) {
array.splice(index, 0, ...elements);
}
In the example, we create an array and add an element to it into index 2:
Javascript Array
Arrays cannot use strings but must use integers. Using non-integers with bracket notation will set or access a variable associated with that array's object property collection. Neither the length of an array nor the types of its elements are fixed. JavaScript arrays are zero-indexed. It means that the first element is at index 0, and the index of the last element is equal to the value of the array's length property minus 1.