So the other day, I came across a leet code problem, which asked me to manipulate an array without making a copy of it! I searched for methods and I remembered, that .splice() can be useful for this problem. So without wasting any time lets dive into the basics of .splice() method.
Deleting A Number from an Array let array = [2,3,4,5,6] //At index 0, let's delete the first number which is 2 in this case! array.splice(0, 1) ==> return value: // returns the removed element ==> console.log(array)// [3,4,5,6] //At index 0, Let's delete, first two numbers which is 2 and 3 array.splice(0, 2) ==> return value:[2,3] ==> console.log(array) // [4,5,6]
In the above example .splice() is taking two parameters:
The index number(the point at which we want to start deleting elements)
The second parameter is the number of elements we want to remove from an array.
Delete elements and add things let array = [2,3,4,5,6] //starting from index one, I want to remove two elements and add chicken array.splice(1,2, "chicken") ==> return value: [ 3, 4 ] ==> console.log(array) // [ 2, 'chicken', 5, 6 ]
Here we are giving .splice(), three parameters, the third parameter is optional. Recap:
- First parameter: Starting index, the point at which you want to delete things
- Second parameter: Number of elements, you want to remove from an array
- Third parameter: Optional, elements you want to add at a specified position
Delete none, Add things let array = [2,3,4,5,6] //At index one, delete nothing (hence 0 as the second parameter), and add few more elements array.splice(1,0,"grandma", "loves", "chicken") ==> return value:  ==> console.log(array) // [ 2, 'grandma', 'loves', 'chicken', 3, 4, 5, 6 ]
When you don’t want to delete anything, just add “0”, to the second parameter.
Replace elements with other things let array = [2,3,4,5,6] //At index 4, replace number 6 with other elements array.splice(4, 1,"grandma", "loves", "eric") ==> return value: [ 6 ] ==> console.log(array)// [ 2, 3, 4, 5, 'grandma', 'loves', 'eric' ]
I hope this blog was helpful! Now go ahead and play around with .splice() until it is clear and also challenge yourself with a leet code problem: Move Zeros.