Get min and max numbers from multidimensional array

If I have an array like this:

array = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]] 

I need to find the max and min values ​​from this array. In this case, max = 33, min = 0

I have seen examples of array reduction, but I do not want to find the maximum value for a specific index of the internal array.

+7
javascript jquery
source share
6 answers

Just try:

 var flat = []; $.map(array, function(item){ $.merge(flat, item); }); // or merge arrays using `join` and `split` var flat = array.join().split(','); var max = Math.max.apply( Math, flat ), min = Math.min.apply( Math, flat ); 
+10
source share

Here is a clean JS based solution. Without jQuery:

 var flattened = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]].reduce(function(a, b) { return a.concat(b); }); Math.max.apply(null, flattened) //33 Math.min.apply(null, flattened) // 0 
+2
source share

Without jquery, using this answer to add max and min to arrays:

 Array.prototype.max = function() { return Math.max.apply(null, this); }; Array.prototype.min = function() { return Math.min.apply(null, this); }; 

The answer will be as follows:

  arr = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]] maxm = arr.map(function(a){return a.max()}).max(); minm = arr.map(function(a){return a.min()}).min(); 
+2
source share
 min = max = array[0][0] for (i in array) for (j in array[i]) { if (array[i][j] > max) max = array[i][j] if (array[i][j] < min) min = array[i][j] } 
+1
source share

You can do it:

 var array=[[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]]; var newArr=array.join().replace(/\[\]/,"").split(',').map(function(x){return +x}); Math.max.apply(null,newArr); // 33 Math.min.apply(null,newArr); // 0 
+1
source share

With underscores:

 var array = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]]; var max = _.chain(array) .flatten() .max() .value() 

Pretty clear explanation to get min.

0
source share

All Articles