Tags
Asked 3 years ago
9 Jun 2021
Views 317
debugger

debugger posted

How to insert an item into an array at a specific index in JavaScript

How to insert an item into an array at a specific index in JavaScript ?
Nilesh

Nilesh
answered Apr 26 '23 00:00

In JavaScript, you can insert an item into an array at a specific index using the splice() method. Here's an example:



const myArray = ['apple', 'banana', 'orange'];

// Insert a new item 'grape' at index 1
myArray.splice(1, 0, 'grape');

// Output the updated array
console.log(myArray); // ['apple', 'grape', 'banana', 'orange']

In this example, we have an array myArray containing three items. To insert a new item 'grape' at index 1 (i.e., between 'apple' and 'banana'), we use the splice() method with the following parameters:

The first parameter is the index where the insertion should start (1 in this case).
The second parameter is the number of items to remove (0 in this case, since we're not removing any items).
The third parameter is the item to insert ('grape' in this case).
After calling splice(), the array myArray will contain the updated items 'apple', 'grape', 'banana', and 'orange'.

Note that splice() modifies the original array in place, so there's no need to assign the result back to the original variable. Also note that the first parameter (the index) can be negative, in which case the insertion starts from the end of the array.
Post Answer