1// for me lol... pls don't delete!
2// use splice to insert element
3// arr.splice(index, numItemsToDelete, item);
4var list = ["hello", "world"];
5list.splice( 1, 0, "bye");
6//result
7["hello", "bye", "world"]
8
1//we can add elements to array using splice
2
3const strings=['a','b','c','d']
4
5//go the 2nd index,remove 0 elements and then add 'alien' to it
6strings.splice(2,0,'alien')
7
8console.log(strings) //["a", "b", "alien", "c", "d"]
9
10//what is the time complexity ???
11//worst case is O(n). if we are adding to end of array then O(1)
12//in our example we added to the middle of array so O(n/2)=>O(n)
1You want the splice function on the native array object.
2
3arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).
4
5In this example we will create an array and add an element to it into index 2:
6
7var arr = [];
8arr[0] = "Jani";
9arr[1] = "Hege";
10arr[2] = "Stale";
11arr[3] = "Kai Jim";
12arr[4] = "Borge";
13
14console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
15arr.splice(2, 0, "Lene");
16console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
17