admin管理员组文章数量:1338198
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);
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?
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);
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?
Share edited Jun 25, 2012 at 13:55 ffleandro asked Jun 25, 2012 at 13:37 ffleandroffleandro 4,0414 gold badges35 silver badges48 bronze badges2 Answers
Reset to default 17I would write it as such:
Math.max.apply(Math, array.map(v => v[0]));
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()
To avoid creating a new array, you can also reduce the array to a single value:
array.reduce((max, current) => Math.max(max, current[0]), -Infinity)
As you can see, we need to add the initial value of -Infinity
, which is returned if the array is empty.
This is a great application for Array.prototype.reduce
:
max = data.reduce(function(previousVal, currentItem, i, arr) {
return Math.max(previousVal, currentItem[0]);
}, Number.NEGATIVE_INFINITY);
This also avoids the bug in your code that would happen if all the values in data
are less than 0
. You should be paring against Number.NEGATIVE_INFINITY
rather than 0
.
Alternatively, you could normalize the data before reducing to the max value:
max = data.map(function (d) {
return d[0];
}).reduce(function (p, c, i, arr) {
return Math.max(p, c);
});
本文标签: mathJavascript max() for array columnStack Overflow
版权声明:本文标题:math - Javascript max() for array column - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743528680a2498668.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论