Calculating excluded average - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>Suppose we have an array of objects like this &minus;</p><pre class="result notranslate">const arr = [ &nbsp; &nbsp;{val: 56, canUse: true}, &nbsp; &nbsp;{val: 16, canUse: true}, &nbsp; &nbsp;{val: 45, canUse: true}, &nbsp; &nbsp;{val: 76, canUse: false}, &nbsp; &nbsp;{val: 45, canUse: true}, &nbsp; &nbsp;{val: 23, canUse: false}, &nbsp; &nbsp;{val: 23, canUse: false}, &nbsp; &nbsp;{val: 87, canUse: true}, ];</pre><p>We are required to write a JavaScript function that calculates the average of the val property of all those objects that have a boolean true set for the canUse flag.</p><h2>Example</h2><p>Following is the code &minus;</p><!---<p><a href="" target="_blank" rel="nofollow" class="demo"><i class="fa-external-link"></i> Live Demo</a></p>---><pre class="prettyprint notranslate">const arr = [ &nbsp; &nbsp;{val: 56, canUse: true}, &nbsp; &nbsp;{val: 16, canUse: true}, &nbsp; &nbsp;{val: 45, canUse: true}, &nbsp; &nbsp;{val: 76, canUse: false}, &nbsp; &nbsp;{val: 45, canUse: true}, &nbsp; &nbsp;{val: 23, canUse: false}, &nbsp; &nbsp;{val: 23, canUse: false}, &nbsp; &nbsp;{val: 87, canUse: true}, ]; const excludedAverage = arr =&gt; { &nbsp; &nbsp;let count = 0, props = 0; &nbsp; &nbsp;for(let i = 0; i &lt; arr.length; i++){ &nbsp; &nbsp; &nbsp; if(!arr[i].canUse){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; props++; &nbsp; &nbsp; &nbsp; count += arr[i].val; &nbsp; &nbsp;}; &nbsp; &nbsp;return (count) / (!props ? 1 : props); }; console.log(excludedAverage(arr));</pre><h2>Output</h2><p>This will produce the following output in console &minus;</p><pre class="result notranslate">49.8</pre>
raja
Updated on 30-Sep-2020 14:08:52

Advertisements