There is no inbuilt method in JavaScript that directly allows for the insertion of an element at any arbitrary index of an array.
This can be solved using these 3 approaches:
The array.splice() method is usually used to add or remove items from an array. This method takes in 3 parameters, the index where the element id is to be inserted or removed, the number of items to be deleted, and the new items that are to be inserted. The only insertion can be done by specifying the number of elements to be deleted to 0. This allows only inserting the specified item at a particular index with no deletion.
Syntax: array.splice(index, no_of_items_to_remove, item1 ... itemX); Example: In this example, we will insert an element at the 2nd index of the array using the splice() method of JavaScript.
Javascript
function insertElement() {
let arr = [1, 2, 3, 4, 5];
let index = 2;
let element = -99;
arr.splice(index, 0, element);
console.log(arr);
}
insertElement();
Output [ 1, 2, -99, 3, 4, 5 ]
The for loop can be used to move all the elements from the index (where the new element is to be inserted) to the end of the array, one place after its current place. The required element can then be placed at the index.
Syntax: // Shift all elements one place to the // back until index for (let i = arr.length; i > index; i--) { arr[i] = arr[i - 1]; } // Insert the element at the index arr[index] = element; Example: In this example, we will insert an element at the 2nd index of the array using the for loop of JavaScript.
Javascript
function insertElement() {
let arr = [1, 2, 3, 4, 5];
let index = 2;
let element = -99;
for (let i = arr.length; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = element;
console.log(arr);
}
insertElement();
Output [ 1, 2, -99, 3, 4, 5 ]
The JavaScript Array concat() Method is used to merge two or more arrays together. This method does not alter the original arrays passed as arguments but instead, returns a new Array.
Syntax: let newArray1 = oldArray.concat() let newArray2 = oldArray.concat(value0) let newArray3 = oldArray.concat(value0,value1) ....... ....... let newArray = oldArray.concat(value1 , [ value2, [ ...,[ valueN]]]) Example: In this example, we have used concat method .
Javascript
function insertItemAtIndex(arr, index, item) {
if (index < 0 || index > arr.length) {
return arr;
}
return arr.slice(0, index)
.concat(item, arr.slice(index));
}
const originalArray = [1, 2, 4, 5];
const newArray = insertItemAtIndex(originalArray, 2, 3);
console.log(newArray);
Last Updated :
15 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...