Retaining array elements greater than cumulative sum using reduce() in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>We are required to write a JavaScript function that takes in an array of Numbers. Our function should return a new array that contains all the elements from the original array that are greater than the cumulative sum of all elements up to that point. We are required to solve this problem using the Array.prototype.reduce() function.</p><h2>Example</h2><p>Let&rsquo;s write the code for this function &minus;</p><pre class="prettyprint notranslate">const arr = [1, 2, 30, 4, 5, 6]; const retainGreaterElements = arr =&gt; { &nbsp; &nbsp;let res = []; &nbsp; &nbsp;arr.reduce((acc, val) =&gt; { &nbsp; &nbsp; &nbsp; return (val &gt; acc &amp;&amp; res.push(val), acc + val); &nbsp; &nbsp;}, 0); &nbsp; &nbsp;return res; } console.log(retainGreaterElements(arr));</pre><h2>Output</h2><p>The output in the console &minus;</p><pre class="result notranslate">[1, 2, 30]</pre>
raja
Updated on 12-Oct-2020 11:13:57

Advertisements