javascript insert element in array code example

Example 1: javascript insert item into array

var colors=["red","blue"];
var index=1;

//insert "white" at index 1
colors.splice(index, 0, "white");   //colors =  ["red", "white", "blue"]

Example 2: javascript push in specific index

arr.splice(index, 0, item);
//explanation:
inserts "item" at the specified "index",
deleting 0 other items before it

Example 3: add elements to an array with splice

var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
  fruits.splice(2, 0, "Lemon", "Kiwi");
  document.getElementById("demo").innerHTML = fruits;
}

Example 4: js insert in array

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]