Javascript max()表示数组列 [英] Javascript max() for array column
问题描述
通常当我需要找到数组的最大值时,我会使用这个非常简单的代码:
var max = Math.max.apply(Math,array);
Usually when I need to find the max value of an array I use this very simple code:
var max = Math.max.apply(Math, array);
但是,现在我有一个多维数组,其中每行我有一个包含5列的数组。是否有类似的方法来查找某列的最大值?
现在我正在做:
However, now I have a multidimensional array in which for each line I have an array with 5 columns. Is there a similar way to find the max value for a certain column? Right now I'm doing:
var maxFunc = function(data){
var max = 0;
data.forEach(function(value){
max = Math.max(max, value[0]);
});
return max;
};
我很好奇是否有更漂亮/更简单的方法吗?
I was curious if there was a prettier/simpler way of doing this?
推荐答案
我会这样写:
Math.max.apply(Math, array.map(function(v) {
return v[0];
}));
array.map
将改变原作基于您的选择逻辑的数组,在这种情况下返回第一项。然后将转换后的数组输入 Math.max()
The array.map
will transform the original array based on your picking logic, returning the first item in this case. The transformed array is then fed into Math.max()
这篇关于Javascript max()表示数组列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!