OneBite.Dev - Coding blog in a bite size

insert an element at a specific index in an array in Javascript

Code snippet on how to insert an element at a specific index in an array in Javascript

  function insertAtIndex(arr, index, element) {
    arr.splice(index, 0, element);
    return arr;
  }

This code uses the splice method to insert an element into an array at a specific index. The first argument of the splice method is the index at which the insertion should occur. The second argument is the number of elements (in this case 0) that should be removed before the insertion occurs. The third argument is the element to be inserted. The splice method then updates the original array and returns it. The function above creates a wrapper function that takes three arguments: an array, the index at which to insert, and the element to be inserted. It then uses the splice method to do the insertion and finally returns the updated array.

javascript