Can you spot the largest number in the following 4x4 array?
[
[1, 2, 2, 5],
[2, 5, 3, 1],
[4, 5, 9, 6],
[1, 0, 7, 3]
]
The answer? 9
We can visually inspect the following 4x4 array to surmise that 9
is the largest value. But, it's more fun (and efficient!) to find the max value programmatically.
Let's use JavaScripts built-in language features to find the maximum value of a multidimensional array.
Find the max by converting multidimensional to a flat array
Use the following approach when working with multidimensional arrays that are not too large in size. Check out the second example if you're working with a large data set, such as a database with many rows and columns.
const MAX_VALUE = 9;
const multidimensionalArray = [
[1, 2, 2, 5],
[2, 5, 3, 1],
[4, 5, MAX_VALUE, 6],
[1, 0, 7, 3]
];
// 1. Convert the multidimensional array to a single, flat array
const flatArray = multidimensionalArray.reduce((acc, innerArray) =>
[...acc, ...innerArray]
);
// 2. Use `Math.max` to find the maximum value within the flat array
Math.max(...flatArray);
// 9
How to find the max of a multidimensional JavaScript array:
- Convert the multidimensional array to a single, flat array
- Use
Math.max
to find the maximum value within the flat array
While this above approach is effective, it's there are more efficient approaches when working with large multidimensional arrays.
Find the max and avoid creating a flat array
const MAX_VALUE = 9;
const multidimensionalArray = [
[1, 2, 2, 5],
[2, 5, 3, 1],
[4, 5, MAX_VALUE, 6],
[1, 0, 7, 3]
];
// Use .reduce() to find the max value within the multidimensional array
const maxArrayValue = multidimensionalArray.reduce((cumulativeMaxValue, innerArray) => {
// Find the max value in the current array
const currentMaxInArray = Math.max(...innerArray);
// Compare the accumlated max value to the current array's max value &
// return the greater of the two values
return Math.max(cumulativeMaxValue, currentMaxInArray);
}, -Infinity);
console.log('Max value in multidimensional array: ', maxArrayValue);
// Max value in multidimensional array: 9
Unlike the first example, this example avoids creating a new flat array. As creating the flat array may cause memory issues when parsing large multidimensional arrays, this example may be more appropriate in certain situations.
However, this example is slightly more complex. For a simple multidimensional array with a known maximum size, consider opting for this article's initial example.