在多维数组javascript或coffeescript中获取最大值 [英] Get largest value in multi-dimensional array javascript or coffeescript
本文介绍了在多维数组javascript或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]]
我需要的是集合的第一个值中的最大数,因此在本例中为 12
.在网上查看一些示例,我看到的最好的方法是:
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
问题是,这只适用于一维数组.我将如何为我的 senario 暗示这一点?(jquery 允许)
Problem is, this only works with single dimensional arrays. How would I impliment this for my senario? (jquery allowed)
最终解决方案:
这不是问题的一部分,但我需要数组中的最小值和最大值,这让事情发生了一些变化.
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
推荐答案
你可以使用 .reduce()
...
array.reduce(function(max, arr) {
return Math.max(max, arr[0]);
}, -Infinity)
<小时>
这是一个不使用 Math.max
...
array.reduce(function(max, arr) {
return max >= arr[0] ? max : arr[0];
}, -Infinity);
...以及 jsPerf 测试.
这篇关于在多维数组javascript或coffeescript中获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文