Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

jquery - Get largest value in multi-dimensional array javascript or coffeescript

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use .reduce()...

array.reduce(function(max, arr) { 
    return Math.max(max, arr[0]); 
}, -Infinity)

Here's a version that doesn't use Math.max...

array.reduce(function(max, arr) {
    return max >= arr[0] ? max : arr[0];
}, -Infinity);

...and a jsPerf test.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...