While working with javascript arrays, often there is a requirement to insert an item at a specific index in javascript. This article will discuss adding an element to an array at a particular index.

Table of Contents:-

Insert element in array at specific position using splice()

Javascript’s splice(startIndex, deleteCount, element1, element2….) method is used to modify the elements of an array by removing or replacing or/and adding new elements to the array.

  • startIndex: is the starting index to make the change in the array.
  • deleteCount: is the number of elements to be deleted from the array. This argument is optional.
  • element1,element2,… : are the elements that will be added. These arguments are optional and used when the splice() method is used to insert elements in the calling array.

Example:-

Insert an element “Most” at 2nd index position of the array [“Javascript”, “Is”, “Popular”,”Language”]

Code:-

let stringArray = ["Javascript", "Is", "Popular","Language"];
stringArray.splice(2, 0, "Most");
console.log(stringArray);

Output:-

[ 'Javascript', 'Is', 'Most', 'Popular', 'Language' ]

Explanation:-

  • Here, the splice(2,0,”Most”) method will start modifying the array from the 2nd index position(first argument). It will delete 0 elements (second argument) and insert “Most” (third argument) in the stringArray.
  • Note that indexes are zero-based in javascript arrays.

Insert element in array at specific position using reduce()

Javascript’s reduce((previousValue, currentValue, currentIndex, array) => { … }, initialValue) method will executes a callback function “reducer” on each element of the array, passing in the return value of the result from previous calculation until all elements from the array are executed. The final result returned after running the reducer on all elements of the array is a single value.

  • previousValue: is the value resulting from the previous call to “reducer” or the callback function.
  • currentValue: value of current element.
  • currentIndex: current index of the array during traversal. It is optional.
  • array: is the array to traverse. It is optional.
  • initialValue: is the value to which¬†previousValue¬†is initialized the first time the callback is called.

Learn More About reduce()

Example:-

Insert an element “Most” at 2nd index position of the array [“Javascript”, “Is”, “Popular”,”Language”]

Code:-

function insertAtIndex(_array, value, index) {
    newArray =[];
    if(index >= _array.length)
    {
        newArray = _array.concat(value)  ;
    }
    else
    {
        newArray= _array.reduce((previous, current, ind) => previous.concat(ind === index ? [value, current] : current), []);
    }
    return newArray ;     
}

//////usage of the function insertAtIndex(_array, value, index)/////
stringArray = insertAtIndex(stringArray,"Most",2);
console.log(stringArray);

Output:-

[ 'Javascript', 'Is', 'Most', 'Popular', 'Language' ]

Explanation:-

  • Here, the code uses the reduce() method to apply a callback function on all elements of the stringArray.
  • The callback function will take a new array with the initial value [] that is an empty array.
  • Then, this callback function will traverse each element of the stringArray and concatenate them one-by-one to the empty array.
  • Within the function, the code checks if the index of the callback function -> ind equals the index passed in insertAtIndex() function. In this case, the new element “Most” is inserted. Else concatenation happens element-by-element of the stringArray.
  • Finally, assign the newArray returned by insertAtIndex() function to stringArray variable and print it on the console.

Read More:

I hope this article helped you insert an element at a specific index in an array in javascript. Good Luck !!!