Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get min-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 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.

like image 902
benjamin54 Avatar asked Apr 09 '14 12:04

benjamin54


2 Answers

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 );
like image 132
hsz Avatar answered Oct 23 '22 20:10

hsz


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
like image 2
dikesh Avatar answered Oct 23 '22 19:10

dikesh