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
Selected Reading
Detecting the largest element in an array of Numbers (nested) in JavaScript
We need to find the largest number in a nested array of any depth. This problem requires recursion to traverse through all nested levels and compare each number to find the maximum value.
For example, if we have this nested array:
const arr = [
34, 65, 67,
[
43, 76, 87, 23, 56, 7,
[
54, 7, 87, 23, 79, 994, 2
],
54
], 54, 4, 2
];
The largest number across all nested levels is 994.
Approach: Using Recursion
We'll use a recursive function that:
- Iterates through each element in the array
- If an element is an array, recursively calls itself on that sub-array
- If an element is a number, compares it with the current maximum
- Returns the largest number found
Example 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 < arr.length; i++){
if(Array.isArray(arr[i])){
greatest = Math.max(greatest, getGreatest(arr[i], greatest));
} else {
if(arr[i] > greatest){
greatest = arr[i];
}
}
}
return greatest;
};
console.log(getGreatest(arr));
994
Alternative: Flatten and Find Max
Another approach is to flatten the nested array first, 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 flattenAndFindMax = (arr) => {
const flattened = arr.flat(Infinity);
return Math.max(...flattened);
};
console.log(flattenAndFindMax(arr));
994
Method Comparison
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
| Recursive approach | Efficient | Moderate | Low |
| Flatten + Math.max | Good for small arrays | High | Higher |
Testing with Edge Cases
// Test with negative numbers
const negativeArr = [-10, [-20, [-30, -5]], -1];
console.log("Negative array max:", getGreatest(negativeArr));
// Test with single element
const singleArr = [42];
console.log("Single element max:", getGreatest(singleArr));
// Test with deeply nested structure
const deepArr = [1, [2, [3, [4, [5]]]]];
console.log("Deep nested max:", getGreatest(deepArr));
Negative array max: -1 Single element max: 42 Deep nested max: 5
Conclusion
The recursive approach efficiently finds the maximum value in nested arrays by traversing each level. For simpler cases, flattening the array first provides a more readable solution, though it uses more memory.
Advertisements
