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)
1// Syntax
2splice(start)
3splice(start, deleteCount)
4splice(start, deleteCount, item1)
5splice(start, deleteCount, item1, item2, itemN)
6
7const months = ['Jan', 'March', 'April', 'June'];
8months.splice(1, 0, 'Feb');
9// inserts at index 1
10console.log(months);
11// expected output: Array ["Jan", "Feb", "March", "April", "June"]
12
13months.splice(4, 1, 'May');
14// replaces 1 element at index 4
15console.log(months);
16// expected output: Array ["Jan", "Feb", "March", "April", "May"]
1let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
2let removed = myFish.splice(3, 1)
3
4// myFish is ["angel", "clown", "drum", "sturgeon"]
5// removed is ["mandarin"]
1let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
2//insert new element into array at index 2
3let removed = myFish.splice(2, 0, 'drum')
4
5// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
6// removed is [], no elements removed
1//Example 1:
2
3//Remove 1 element at index 3
4let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
5let removed = myFish.splice(3, 1)
6
7//Result
8// myFish is ["angel", "clown", "drum", "sturgeon"]
9// removed is ["mandarin"]
10
11//Example 2:
12
13//Remove 1 element at index 2, and insert "trumpet"
14let myFish = ['angel', 'clown', 'drum', 'sturgeon']
15let removed = myFish.splice(2, 1, 'trumpet')
16
17//Result
18// myFish is ["angel", "clown", "trumpet", "sturgeon"]
19// removed is ["drum"]