Upper or lower elements count in an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>Consider we have an array of Numbers that looks like this &minus;</p><pre class="result notranslate">const array = [54,54,65,73,43,78,54,54,76,3,23,78];</pre><p>We are required to write a function that counts how many of the elements are in the array below / above a given number.</p><p>For example, if the number is 60 &minus;</p><p>The answer should be 5 elements below it (54,54,43,3,23) and 5 element par it (65,73,78,76,78) Therefore, let&rsquo;s write the code for this function &minus;</p><h2>Example</h2><p>The code for this will be &minus;</p><pre class="prettyprint notranslate">const array = [54,54,65,73,43,78,54,54,76,3,23,78]; const belowParNumbers = (arr, num) =&gt; { &nbsp; &nbsp;return arr.reduce((acc, val) =&gt; { &nbsp; &nbsp; &nbsp; const legend = [&#39;par&#39;, &#39;below&#39;]; &nbsp; &nbsp; &nbsp; const isBelow = val &lt; num; &nbsp; &nbsp; &nbsp; acc[legend[+isBelow]]++; &nbsp; &nbsp; &nbsp; return acc; &nbsp; &nbsp;}, { &nbsp; &nbsp; &nbsp; below: 0, &nbsp; &nbsp; &nbsp; par: 0 &nbsp; &nbsp;}); }; console.log(belowParNumbers(array, 50)); console.log(belowParNumbers(array, 60)); console.log(belowParNumbers(array, 70));</pre><h2>Output</h2><p>The output in the console will be &minus;</p><pre class="result notranslate">{ below: 3, par: 9 } { below: 7, par: 5 } { below: 8, par: 4 }</pre>
raja
Updated on 20-Oct-2020 11:37:33

Advertisements