Skip to main content

Archive

Show more

How to insert an item into an array at a specific index in JavaScript

how-to-insert-item-into-array-at-a-specific-index-in-javascript


Question: How to insert an item into an array at a specific index in JavaScript

Answer:

First Method:

myArray = ["Red","Green", "Black", "Orange", "Yellow"];

myArray.splice(4, 0, "Blue");
console.log(myArray.join());

Output:

["Red", "Green", "Black", "Orange", "Blue", "Yellow"]




Second Method:

myArray = ["Red","Green", "Black", "Orange", "Yellow"];
Array.prototype.insertItem = function ( index, item ) {
  this.splice( index, 0, item );
};

myArray.insertItem(4, 'Blue');
console.log(myArray);

Output:

["Red", "Green", "Black", "Orange", "Blue", "Yellow"]


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments