Get largest value in multi-dimensional array javas

2019-01-11 14:46发布

I have an array that looks like the following:

array = [[1, 5], [4, 7], [3, 8], [2, 3],  
 [12, 4], [6, 6], [4, 1], [3, 2], 
 [8, 14]]

What I need is the largest number from the first value of the sets, so in this case 12. Looking at some examples online, the best way I saw to accomplish this is :

Math.max.apply Math, array

Problem is, this only works with single dimensional arrays. How would I impliment this for my senario? (jquery allowed)


The end solution:

It wasn't part of the question, but I needed both the min and max from the array, and that changes things a little.

    unless device.IE
        justTheDates    = magnitudeArray.map (i) -> i[0]
        @earliest       = Math.min.apply Math, justTheDates
        @latest         = Math.max.apply Math, justTheDates                 
    else
        @earliest       = magnitudeArray[0][0]
        @latest         = magnitudeArray[0][0]
        for magnitudeItem in magnitudeArray
            @earliest   = magnitudeItem[0] if magnitudeItem[0] < @earliest
            @latest     = magnitudeItem[0] if magnitudeItem[0] > @latest

8条回答
神经病院院长
2楼-- · 2019-01-11 15:19

Using a comprehension in CoffeeScript:

Math.max.apply Math, (x[0] for x in array)

Running example

查看更多
Ridiculous、
3楼-- · 2019-01-11 15:19

I know this is an old post, but if you (or someone else) want the largest number in the whole array, try with:

var array = [[1, 5], [4, 7], [3, 8], [2, 3],  
 [12, 4], [6, 6], [4, 1], [3, 2], 
 [8, 14]];

var max = array.reduce(function (max, arr) {
    return max >= Math.max.apply(max, arr) ? max : Math.max.apply(max, arr);
}, -Infinity);
console.log(max);

In this examlpe, it will return the value 14.

查看更多
登录 后发表回答