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
Finding the maximum in a nested array - JavaScript
Let's say, we have to write a simple function in JavaScript that takes in the following array of Numbers (nested to any level) ?
const arr = [
15, 24,
[
29, 85, 56,
[
36, 14, 6, 98, 34, 52
],
22
], 87, 60
];
and return the greatest number present in the array.
For 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
We will use recursion to find the greatest number in the array. The key is to flatten the nested structure and compare all values.
Using Recursion with Math.max()
Here's an efficient approach using recursion and the spread operator:
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) => {
let max = -Infinity;
for (let i = 0; i
994
Using Array.flat() Method
A simpler approach using the built-in flat() method with Infinity depth:
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) => {
return Math.max(...arr.flat(Infinity));
};
console.log(getGreatest(arr));
994
Using Reduce with Recursion
Another recursive approach using the reduce method:
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) => {
return arr.reduce((max, current) => {
if (Array.isArray(current)) {
return Math.max(max, getGreatest(current));
}
return Math.max(max, current);
}, -Infinity);
};
console.log(getGreatest(arr));
994
Comparison of Methods
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| Recursion with Math.max() | Good | Good | All browsers |
| Array.flat() + Math.max() | Excellent | Best | ES2019+ |
| Reduce with recursion | Good | Good | All browsers |
Conclusion
For finding the maximum value in nested arrays, Array.flat(Infinity) with Math.max() provides the cleanest solution. For broader browser compatibility, use the recursive approach with Math.max().
