js insert at index code example

Example 1: add element to array using splice

//we can add elements to array using splice

const strings=['a','b','c','d']

//go the 2nd index,remove 0 elements and then add 'alien' to it
strings.splice(2,0,'alien')

console.log(strings) //["a", "b", "alien", "c", "d"]

//what is the time complexity ???
//worst case is O(n). if we are adding to end of array then O(1)
//in our example we added to the middle of array so O(n/2)=>O(n)

Example 2: 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 3: add new element by index js

const arr = [ 1, 2, 3, 4 ];
arr[5] = 'Hello, world!';

console.log(arr); // [ 1, 2, 3, 4, <1 empty item>, 'Hello, world!' ]
console.log(arr.length); // 6