The direct insertion of a new element into an array at any given index is not supported by any built-in method. To do so, use the “splice()” method, which modifies an array’s contents by eliminating, adding, or replacing new items at any specified index. It also updates the array that invokes it rather than creating a new one.
Use the given syntax for the splice() method:
In the above syntax:
- The “index” is where the new element will be positioned.
- The “no_of_EliminatedItems” is the number of elements that must be removed from the array. It is an optional argument.
- The “item1, … itemN” are the elements that will be added to an array.
The splice() method returns an updated array with new elements at the specific index.
Example 1: Add an Element to an Array at a Specific Index Using the splice() Method
Create an array “number”:
Call the “splice()” method by passing index “3” as the first argument which is the starting index of the elements that will be added in an array, “0” as a second argument, which indicates no element will be deleted from the array, and then “3, 4, 5” are the elements that need to be added in an array:
Print the updated array on the console using the “console.log()” method:
The output indicates that the elements are successfully added to an array from index 3.
Example 2: Add an Array to an Array at a Specific Index Using the splice() Method
Create an array “num” and add all of its elements in the “number” array:
Use the spread operator (…) in the splice() method as a third argument that will copy all the elements of the “num” array into the “number” array:
Print the resultant array on the console:
The above output shows that all elements of an array “num” are successfully added in the “number” array at the 3rd index.