This post will discuss how to push an item to a specific index in an array in JavaScript.

There are several ways to insert an element into an array at a specific index in JavaScript, depending on the performance, readability, and compatibility of the code. Here are some of the methods that we can use, along with some examples:

1. Using splice() function

The Array.splice() is a built-in function that can add or remove elements from an array at a given index. To insert an element, we need to pass three arguments to the splice function: the index where we want to insert the element, the number of elements to delete (zero if we don’t want to delete anything), and the element to insert. Here’s an example:

Download  Run Code

 
In this example, splice() is called on the array arr. The first argument 1 specifies the index at which the element should be inserted. The second argument 0 indicates that no elements should be removed. The third argument "mango" is the element to be inserted. Here’s another example of how we can use it:

Download  Run Code

 
A cleaner approach is to create a custom function for array insertion. We can add a custom function insert() to the Array. which takes two arguments: index and item, and uses splice() to insert the item at the specified index. Here’s an example of how we can achieve it:

Download  Run Code

 
This function is compatible with older browsers and can also be used to remove or replace elements. However, it modifies the original array and may not be very efficient for large arrays.

2. Using spread operator

The spread operator is an ES6 feature that can spread an array into individual elements. We can use it to create a new array that contains the original array elements and the inserted element at a specific index. To do this, we need to use a pair of square brackets to enclose the spread operator and the array, and use the slice() function to get the subarrays before and after the index. Here’s an example:

Download  Run Code

 
This function is concise and expressive, but it requires ES6 support or a transpiler for older browsers. It also creates a new array instead of modifying the original one.

3. Using a for loop

This is another way that involves shifting all the elements from the index (where we want to insert the element) to the end of the array, one place after their current position. Then, we can assign the element to the index. Here’s an example:

Download  Run Code

 
This function is compatible with older browsers and modify the original array. However, it may not be very elegant or concise for this task.

That’s all about pushing an item to a specific index in an array in JavaScript.