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
How Do I Find the Largest Number in a 3D JavaScript Array?
To find the largest number in a 3D JavaScript array, we can use flat(Infinity) to flatten all nested levels, then apply Math.max() to find the maximum value.
The Problem
3D arrays contain multiple levels of nested arrays, making it difficult to directly compare all numbers. We need to flatten the structure first.
var theValuesIn3DArray = [75, [18, 89], [56, [97], [99]]];
Using flat() with Math.max()
The flat(Infinity) method flattens all nested levels, and the spread operator ... passes individual elements to Math.max().
var theValuesIn3DArray = [75, [18, 89], [56, [97], [99]]];
Array.prototype.findTheLargestNumberIn3dArray = function (){
return Math.max(...this.flat(Infinity));
}
console.log("The largest number in 3D array is=");
console.log(theValuesIn3DArray.findTheLargestNumberIn3dArray());
The largest number in 3D array is= 99
Alternative Method: Without Prototype Extension
You can achieve the same result without extending the Array prototype:
var theValuesIn3DArray = [75, [18, 89], [56, [97], [99]]];
function findLargestIn3DArray(arr) {
return Math.max(...arr.flat(Infinity));
}
console.log("The largest number is:", findLargestIn3DArray(theValuesIn3DArray));
The largest number is: 99
How It Works
-
flat(Infinity)recursively flattens the array to a single level:[75, 18, 89, 56, 97, 99] - The spread operator
...expands the flattened array as individual arguments -
Math.max()compares all numbers and returns the largest
Handling Edge Cases
// Empty array console.log(Math.max(...[].flat(Infinity))); // -Infinity // Array with non-numbers (they become NaN) var mixedArray = [10, [20, "hello"], [30]]; console.log(Math.max(...mixedArray.flat(Infinity))); // NaN
-Infinity NaN
Conclusion
Use Math.max(...array.flat(Infinity)) to find the largest number in multi-dimensional arrays. The flat(Infinity) method handles any nesting depth efficiently.
Advertisements
