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

  1. flat(Infinity) recursively flattens the array to a single level: [75, 18, 89, 56, 97, 99]
  2. The spread operator ... expands the flattened array as individual arguments
  3. 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.

Updated on: 2026-03-15T23:18:59+05:30

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements