jQuery splice function for splitting the javascript array

We have splice() method in jQuery to split the javascript array in a simple way. This will helpful when you want to perform different actions on the different parts of javascript array.

 

jQuery splice() method requires two parameters, the first parameter is the index of the item from where to start splitting and second parameter is the number of items to be removed from the array after the specified index.

 

jQuery splice() method syntax:

                                                    subarray = array.splice(i,n);

 

Where i the index of the item from where we have to start the splitting and n is the number of elements to be removed from original array after the specified index i.

 

Here I am explaining simple example by using splice() method.

 

<html>
    <head>
        <title>javascript arrays using jQuery splice() method</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                //SPliting array using splice method
                var elems = ['Asp.Net', 'Vb.Net', 'C#.Net', 'Asp.Net MVC', 'Sharepoint']
                //orginal array
                $('#divo').html(elems.join('<br/>'));

                //spliting the array
                var elems2 = elems.splice(1, 2);

                //split part
                $('#div1').html(elems2.join('<br/>'));

                //remaining part
                $('#div2').html(elems.join('<br/>'));
           
            });   
        </script>
    </head>
    <body>
        <p>Original Array</p>
        <div id="divo"></div>
        <p>1st Part of the array</p>
        <div id="div1"></div>
        <p>2nd Part of the array</p>
        <div id="div2"></div>
    </body>
 </html>

 

In the above code we have original array "elems" and we are assigning this array to the <div> tag whose id is "divo" one by one by using  $('#divo').html(elems.join('<br/>'));


We are splitting this array by using splice method as shown below.

                              var elems2 = elems.splice(1, 2);


Here we are splitting the "elems" array and assigning part of the array to the new array "elems2". When we split the some part of from the main array and assigning to the new array, the remaining part will be assign to the main array automatically. That means here remaining part will be placed in the main array "elems" only.

 

After splitting the array we are assigning the first part to the "div1" <div> tag by using $('#div1').html(elems2.join('<br/>')); and remaining part to the "div2" <div> tag by using $('#div2').html(elems.join('<br/>'));.

 

Download source code: jQuery_splice.zip (35.79 kb)