How to insert an element in a specific index in JavaScript Array

We have some built-in methods to add elements at the beginning and end of an array:

  • push(value) → Adds an element to the end of an array.
  • unshift(value) → Adds an element to the beginning of an array.

There is no method available in the Array object to add an element to a specific index, but we can use the already available splice method to achieve this.

An array starts from index 0, so if we want to add an element as the first element of the array, then the index of the element is 0. If we want to add an element to the nth position, then the index is the (n - 1)th index.

Note: The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in the original array (i.e., the source array is modified).

The splice() method takes three arguments:

  • start → The index at which to start changing the array.

  • deleteCount (optional) → An integer that indicates the number of elements in the array to remove from the start.

  • (elem1, elem2 …) → The elements to add to the array, starting at the beginning. If you do not specify any elements, splice() will only remove elements from the array.

In order to insert an element in the specific index, we need to provide the arguments as:

  • start → the index in which to insert the element.
  • deleteCount → 0 (because we don’t need to delete any elements).
  • elem → elements to insert.

Let’s write the function:

function insertAt(array, index, ...elementsArray) {
    array.splice(index, 0, ...elementsArray);
}

Now, let’s call the function:

var num = [1,2,3,6,7,8];

/* say we need to insert 4,5 before 6 in the above array
 * 1. source array - num
 * 2. index to insert - 3
 * 3. remaining are elements to insert
*/

insertAt(num, 3, 4, 5); // [1,2,3,4,5,6,7,8]

function insertAt(array, index, ...elementsArray) {
array.splice(index, 0, ...elementsArray);
}
var num = [1,2,3,6,7,8];
console.log("The array is", num);
console.log("\n--------\nAdding 4 and 5 before 6 in the above array");
insertAt(num, 3, 4, 5);
console.log("After adding elements the array is", num);
Attributions:
  1. undefined by undefined