Greatest element in a Multi-Dimensional Array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>We have to write a simple function in JavaScript that takes in an array of Numbers (nested to any level) and return the greatest number present in the array.</p><h2>For example:</h2><p>If the input array is &minus;</p><pre class="result notranslate">const arr = [ &nbsp; &nbsp;34, 65, 67, &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; 43, 76, 87, 23, 56, 7, &nbsp; &nbsp; &nbsp; [ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;54, 7, 87, 23, 79, 994, 2 &nbsp; &nbsp; &nbsp; ], &nbsp; &nbsp; &nbsp; 54 &nbsp; &nbsp;], 54, 4, 2 ];</pre><p>Then the output should be &minus;</p><pre class="result notranslate">994</pre><p>We will use recursion to find the greatest number in the array,</p><p>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 arr = [ &nbsp; &nbsp;34, 65, 67, &nbsp; &nbsp;[ &nbsp; &nbsp; &nbsp; 43, 76, 87, 23, 56, 7, &nbsp; &nbsp; &nbsp; [ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;54, 7, 87, 23, 79, 994, 2 &nbsp; &nbsp; &nbsp; ], &nbsp; &nbsp; &nbsp; 54 &nbsp; &nbsp;], 54, 4, 2 ]; const getGreatest = (arr, greatest = -Infinity) =&gt; { &nbsp; &nbsp;for(let i = 0; i &lt; arr.length; i++){ &nbsp; &nbsp; &nbsp; if(Array.isArray(arr[i])){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return getGreatest(arr[i], greatest); &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; if(arr[i] &gt; greatest){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;greatest = arr[i]; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;}; &nbsp; &nbsp;return greatest; }; console.log(getGreatest(arr));</pre><h2>Output</h2><p>The output in the console will be &minus;</p><pre class="result notranslate">994</pre>
raja
Updated on 20-Oct-2020 12:04:11

Advertisements