7

If I have an array like this:

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

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

I saw examples of array reduce, but I don't want to find max value for particular index of the inner array.

Cœur
  • 32,421
  • 21
  • 173
  • 232
benjamin54
  • 1,170
  • 4
  • 24
  • 46

6 Answers6

10

Just try with:

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 );
hsz
  • 136,835
  • 55
  • 236
  • 297
2

Here is pure 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
dikesh
  • 2,075
  • 2
  • 13
  • 23
2

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 becomes:

 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();
Community
  • 1
  • 1
Raul Guiu
  • 2,285
  • 20
  • 34
2

You can do this:

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
Amit Joki
  • 53,955
  • 7
  • 67
  • 89
1
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]    
    }
Jeff B
  • 7,565
  • 15
  • 53
  • 128
alansammarone
  • 21
  • 1
  • 3
0

With underscorejs:

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

Pretty self explanatory to get min.

Seth Malaki
  • 4,298
  • 21
  • 47