To insert an item into an array at a specific index in JavaScript, you can use the splice() method. The splice() method allows you to modify the original array by adding, removing or replacing elements.
Here's an example of how to insert an item into an array at a specific index:
let myArray = ['apple', 'banana', 'orange', 'pear'];
// insert 'kiwi' at index 2
myArray.splice(2, 0, 'kiwi');
console.log(myArray); // Output: ['apple', 'banana', 'kiwi', 'orange', 'pear']
In the example above, we use the splice() method to insert the string 'kiwi' at index 2 of the array. The first argument to the splice() method is the index where we want to insert the item. The second argument is the number of elements we want to remove (in this case, we don't want to remove any elements). The third argument is the item we want to insert.
After the splice() method is called, the item 'kiwi' is inserted at index 2 of the array, and all the remaining elements are shifted to the right.
If you want to replace an element at a specific index instead of inserting a new one, you can use the splice() method with a non-zero second argument. For example, to replace the item at index 1 with the string 'cherry', you could use the following code:
let myArray = ['apple', 'banana', 'orange', 'pear'];
// replace 'banana' with 'cherry' at index 1
myArray.splice(1, 1, 'cherry');
console.log(myArray); // Output: ['apple', 'cherry', 'orange', 'pear']
In this example, we use the splice() method to replace the item at index 1 with the string 'cherry'. The first argument to the splice() method is the index where we want to start the replacement. The second argument is the number of elements we want to remove (in this case, we want to remove one element). The third argument is the item we want to insert in place of the removed element.
Comments (0)