How to join two arrays in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

<p>Following is the code to join two arrays together in JavaScript &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/Le7xmDuk" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Document&lt;/title&gt; &lt;style&gt; &nbsp; &nbsp;body { &nbsp; &nbsp; &nbsp; font-family: &quot;Segoe UI&quot;, Tahoma, Geneva, Verdana, sans-serif; &nbsp; &nbsp;} &nbsp; &nbsp;.result,.sample { &nbsp; &nbsp; &nbsp; font-size: 18px; &nbsp; &nbsp; &nbsp; font-weight: 500; &nbsp; &nbsp; &nbsp; color: rebeccapurple; &nbsp; &nbsp;} &nbsp; &nbsp;.result { &nbsp; &nbsp; &nbsp; color: red; &nbsp; &nbsp;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Join two arrays in JavaScript&lt;/h1&gt; &lt;div class=&quot;sample&quot;&gt;&lt;/div&gt; &lt;div class=&quot;result&quot;&gt;&lt;/div&gt; &lt;button class=&quot;Btn&quot;&gt;CLICK HERE&lt;/button&gt; &lt;h3&gt;Click the above button to join the above two arrays together.&lt;/h3&gt; &lt;script&gt; &nbsp; &nbsp;let BtnEle = document.querySelector(&quot;.Btn&quot;); &nbsp; &nbsp;let resEle = document.querySelector(&quot;.result&quot;); &nbsp; &nbsp;let sampleEle = document.querySelector(&quot;.sample&quot;); &nbsp; &nbsp;let arr = [1, 2, 3, 4]; &nbsp; &nbsp;let arr1 = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]; &nbsp; &nbsp;sampleEle.innerHTML = &quot;arr = &quot; + arr + &quot; &quot; + &quot;arr1 = &quot; + arr1; &nbsp; &nbsp;let mergedArr = arr.concat(arr1); &nbsp; &nbsp;BtnEle.addEventListener(&quot;click&quot;, () =&gt; { &nbsp; &nbsp; &nbsp; resEle.innerHTML = &quot;Merged array = &quot; + mergedArr; &nbsp; &nbsp;}); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</pre><h2>Output</h2><p>The above code will produce the following output &minus;</p><p style=""><img src="https://www.tutorialspoint.com/assets/questions/media/40282/join_two_arrays1.jpg" class="fr-fic fr-dib" width="598" height="219"></p><p>On clicking the &lsquo;CLICK HERE&rsquo; button &minus;</p><p style=""><img src="https://www.tutorialspoint.com/assets/questions/media/40282/join_two_arrays2.jpg" class="fr-fic fr-dib" width="595" height="237"></p>
raja
Updated on 18-Jul-2020 09:03:20

Advertisements