How to reduce arrays in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

<p>Following is the code to reduce arrays in JavaScript &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/J1etMzsC " rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">&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, &nbsp; &nbsp;.sample { &nbsp; &nbsp; &nbsp; font-size: 18px; &nbsp; &nbsp; &nbsp; font-weight: 500; &nbsp; &nbsp; &nbsp; color: red; &nbsp; &nbsp;} &nbsp; &nbsp;.result { &nbsp; &nbsp; &nbsp; color: blueviolet; &nbsp; &nbsp;} &nbsp; &nbsp;button { &nbsp; &nbsp; &nbsp; padding: 8px; &nbsp; &nbsp;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Reduce arrays javascript&lt;/h1&gt; &lt;div&gt;&lt;pre class=&quot;sample&quot;&gt;[1,3,5,6,9,22,15]&lt;/pre&gt;&lt;/div&gt; &lt;div class=&quot;result&quot;&gt;&lt;/div&gt; &lt;button class=&quot;Btn&quot;&gt;Sum&lt;/button&gt; &lt;h3&gt;Click on the above button to sum the elements of the array&lt;/h3&gt; &lt;script&gt; &nbsp; &nbsp;let resEle = document.querySelector(&quot;.result&quot;); &nbsp; &nbsp;let BtnEle = document.querySelector(&quot;.Btn&quot;); &nbsp; &nbsp;let sampleEle = document.querySelector(&quot;.sample&quot;); &nbsp; &nbsp;let arr = [1, 3, 5, 6, 9, 22, 15]; &nbsp; &nbsp;sampleEle.innerHTML = arr; &nbsp; &nbsp;BtnEle.addEventListener(&quot;click&quot;, () =&gt; { &nbsp; &nbsp; &nbsp; resEle.innerHTML = &nbsp; &nbsp; &nbsp; &quot;Sum = &quot; + &nbsp; &nbsp; &nbsp; arr.reduce((sum, prev) =&gt; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return sum + prev; &nbsp; &nbsp; &nbsp; }); &nbsp; &nbsp;}); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</pre><h2>Output</h2><p><img src="https://www.tutorialspoint.com/assets/questions/media/40126/reduce_arrays.jpg" class="fr-fic fr-dib" style="width: 435px; height: 134.85px;" width="435" height="134.85"></p><p>On clicking the &lsquo;Sum&rsquo; button &minus;</p><p><img src="https://www.tutorialspoint.com/assets/questions/media/40126/reduce_arrays1.jpg" class="fr-fic fr-dib" style="width: 458px; height: 156.992px;" width="458" height="156.992"></p>
raja
Updated on 17-Jul-2020 07:40:50

Advertisements