The Power of Splice ( ) Array method

The Power of Splice ( ) Array method

let sports = [ "football" , "basketball" , "swimming", "cricket"]

Whenever we initialize any variable as an array, then that array variable holds many methods for its manipulation.

There are almost four methods which you can use to transform the array :

  1. .push( ) adds items to the end of the array.

  2. .pop() delete an item from the last index of the array.

  3. .shift() delete the item from first index.

  4. .unshift Add the new item at the beginning.

When I was learning array, recalling these methods was very tough and I always use to google out for the them.

But there is a single function which can perform all the 4 functions mentioned above.

.splice() can perform insertion, deletion, replacement.

Syntax

arr.splice( startIndex , deleteCount , elem* , elem* )

sports.splice ( 1 , 2,"running" )

The syntax looks complicated but let's see what each of these argument means

  • startIndex - The index of the element from where you want to modify the array.

  • deleteCount - The no of the element you want to delete fromstartIndex including startIndex too.

Example :

sports.split(1, 2)

Screenshot 2020-10-19 224341.jpg

so the deletion count from basketball which is at 1 index (startIndex) to swimming (2 index).

  • elem - You can also add many elements to the array from startIndex and it is optional.

for example :

Screenshot 2020-10-19 230115.jpg

If you want to add element but without any deletion of element from the array.

You can set deleteCount to 0and all element will be added to the array.

Screenshot 2020-10-19 230817.jpg

You'll notice that the element basketball which was previously at index 1 pushed back to another index after all the element added.

So .splice is doing all that for you in one line of function.

  • As we already know,.push( ) adds items to the end of the array.

So lets perform .push( ) using splice( )

Screenshot 2020-10-19 232041.jpg

  • .pop( ) using splice( )

Screenshot 2020-10-19 233931.jpg

  • .shift( ) delete the element from the first index , lets use splice( ) for the same.

Screenshot 2020-10-19 234213.jpg

  • To add the element at the beginning we use .unshift( ) but this can also be done by .splice( ).

Screenshot 2020-10-19 235059.jpg

So the .splice( ) can perform all the operations and it is very pretty easy to remember.

meanwhile .splice( ) tenor.gif

Thank you :)