jQuery concat() method for combining two javascript arrays

In my previous article, I explained about how to split javascript array. In this article I am explaining about how to combine two javascript arrays by using one of the jQuery methods.

 

jQuery provides us one simple method called concat() which combines two javascript arrays and produce one new array which contains all items of remaining two javascript arrays.

 

Syntax of jQuery concat() method:

                                                        arr3 = arr1.concat(arr2); //arr1,arr2 and arr3 are javascript arrays

 

Here arr1 is invoking the concat() method and we are passing arr2 as a parameter to that method. That results one new array arr3 by combining two arrays arr1, arr2.

 

I am explaining jQuery concat() method with simple example.

 

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

                //Second array
                $('#div2').html(elems2.join('<br/>'));

                //Adter combining two arrays
                var elems = elems1.concat(elems2);
                $('#div12').html(elems.join('<br/>'));

            });   
        </script>
    </head>
    <body>
        <p><b>First Array</b></p>
        <div id="div1"></div>
        <p><b>Second array</b></p>
        <div id="div2"></div>
        <p><b>After combining the two arrays</b></p>
        <div id="div12"></div>
    </body>
 </html>

 

As shown above, we have two arrays elems, elems2. We are assigning these two arrays to two different <div> tags div1 and div2.

 var elems = elems1.concat(elems2); is combining the two arrays elems1, elems2 and assigning the result array to elems. Here elems1 is invoking the concat() jQuery method and we are passing the elems2 array as a parameter. The resulting array contains all elements of elems1, elems2 arrays.

 

Download source code: jQuery_concat.zip (35.78 kb)