

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Greatest element in a Multi-Dimensional Array in JavaScript
<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 −</p><pre class="result notranslate">const arr = [ 34, 65, 67, [ 43, 76, 87, 23, 56, 7, [ 54, 7, 87, 23, 79, 994, 2 ], 54 ], 54, 4, 2 ];</pre><p>Then the output should be −</p><pre class="result notranslate">994</pre><p>We will use recursion to find the greatest number in the array,</p><p>Therefore, let’s write the code for this function −</p><h2>Example</h2><p>The code for this will be −</p><pre class="prettyprint notranslate">const arr = [ 34, 65, 67, [ 43, 76, 87, 23, 56, 7, [ 54, 7, 87, 23, 79, 994, 2 ], 54 ], 54, 4, 2 ]; const getGreatest = (arr, greatest = -Infinity) => { for(let i = 0; i < arr.length; i++){ if(Array.isArray(arr[i])){ return getGreatest(arr[i], greatest); }; if(arr[i] > greatest){ greatest = arr[i]; } }; return greatest; }; console.log(getGreatest(arr));</pre><h2>Output</h2><p>The output in the console will be −</p><pre class="result notranslate">994</pre>
- Related Questions & Answers
- Multi-Dimensional Array in Javascript
- Converting multi-dimensional array to string in JavaScript
- Multi Dimensional Arrays in Javascript
- Reduce a multi-dimensional array in Numpy
- Flattening multi-dimensional arrays in JavaScript
- Sort in multi-dimensional arrays in JavaScript
- What is a multi-dimensional array in C language?
- Reduce a multi-dimensional array along given axis in Numpy
- Reduce a multi-dimensional array along axis 1 in Numpy
- Reduce a multi-dimensional array along negative axis in Numpy
- Reduce a multi-dimensional array and multiply elements in Numpy
- Reduce a multi-dimensional array and add elements in Numpy
- Multi-dimensional lists in Python
- What is the simplest multi-dimensional array in C#?
- Merging duplicate values into multi-dimensional array in PHP
Advertisements