Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Greatest element in a Multi-Dimensional Array in JavaScript
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.
Problem Example
If the input array is:
const arr = [
34, 65, 67,
[
43, 76, 87, 23, 56, 7,
[
54, 7, 87, 23, 79, 994, 2
],
54
], 54, 4, 2
];
Then the output should be:
994
Approach
We will use recursion to traverse through all nested levels of the array. The algorithm checks each element - if it's a number, we compare it with the current greatest; if it's an array, we recursively call the function on that sub-array.
Solution with Corrected Logic
The original approach had a logical error. Here's the corrected implementation:
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 greatest){
greatest = arr[i];
}
}
}
return greatest;
};
console.log(getGreatest(arr));
994
Alternative Approach Using Array.flat()
For modern JavaScript environments, you can use the Array.flat() method to flatten the array completely and then find the maximum:
const arr = [
34, 65, 67,
[
43, 76, 87, 23, 56, 7,
[
54, 7, 87, 23, 79, 994, 2
],
54
], 54, 4, 2
];
const getGreatestFlat = (arr) => {
const flatArray = arr.flat(Infinity);
return Math.max(...flatArray);
};
console.log(getGreatestFlat(arr));
994
Comparison of Approaches
| Method | Performance | Browser Support | Readability |
|---|---|---|---|
| Recursive approach | Good | All browsers | Moderate |
| Array.flat() + Math.max() | Excellent | ES2019+ | High |
How the Recursive Solution Works
The recursive function works by:
- Iterating through each element in the array
- If the element is an array, recursively call the function and compare the result with the current greatest
- If the element is a number, compare it directly with the current greatest
- Return the final greatest value found
Conclusion
Both approaches effectively find the greatest element in multi-dimensional arrays. The recursive solution provides better browser compatibility, while Array.flat() offers cleaner, more readable code for modern environments.
