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)
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
1Check Out my CODE-PEN for this Solution
2
3https://codepen.io/siddhyaOP/pen/eYgRGOe
4https://codepen.io/siddhyaOP/pen/eYgRGOe
5https://codepen.io/siddhyaOP/pen/eYgRGOe
1const numbers = [2, 4, 5, 3, 8, 9, 11, 33, 44];
2const spliceNumbers = numbers.splice(0, 5)
3//start from 0 && remove next 5 elements
4console.log(spliceNumbers)
5//Expected output:[ 2, 4, 5, 3, 8 ]
1Splice and Slice both are Javascript Array functions. Splice vs Slice. The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.27-Jan-2018