In JavaScript, you can use the Array.prototype.splice()
method to insert an item into an array at a specific index.
The splice()
method takes three arguments: the index at which to start changing the array (this is where you want to insert the item), the number of items to remove (this should be 0 when you’re inserting an item), and the item(s) to insert.
Here’s an example of how you can use the splice()
method to insert the number 42 at index 2 of an array:
var numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 0, 42);
console.log(numbers); // output: [1, 2, 42, 3, 4, 5]
You can also insert multiple items at once by passing more than one item as the third argument to the splice()
method:
var numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 0, 42, 43, 44);
console.log(numbers); // output: [1, 2, 42, 43, 44, 3, 4, 5]
It’s important to note that the splice()
method modifies the original array, so after you call the splice()
method, the item(s) will be inserted at the specified index and the remaining elements will be shifted to the right.
You can also use spread operator to insert an item into array at a specific index
let numbers = [1, 2, 3, 4, 5];
let index = 2;
numbers = [...numbers.slice(0, index), 42, ...numbers.slice(index)];
console.log(numbers); // output: [1, 2, 42, 3, 4, 5]
It will return a new array with the element added to the specified index.
In both case, Keep in mind that if the index passed to the splice method is greater than the length of the array, the new element(s) will be added to the end of the array.