如何在javascript中查找嵌套数组的最大/最小值? [英] How to find the max/min of a nested array in javascript?
问题描述
我想要找到嵌套数组的最大值,如下所示:
a = [[1,2] ,[20,3]]
d3.max(d3.max(a))// 20
$ b b
但我的数组包含一个我想要丢弃的文本字段:
a = [[yz,1 ,2],[xy,20,3]]
d3.max(a)// 20
<如果你有一个嵌套的数字数组( arrays = [[1,2],[20,3]]
),嵌套 d3.max :
var max = d3.max(array,function(array){
return d3.max(array);
});
或同等地,使用 array.map :
var max = d3.max array.map(function(array){
return d3.max(array);
}));
如果要忽略字符串值,可以使用 array.filter 忽略字符串:
var max = d3.max(array,function(array){
return d3.max(array.filter(function){
return typeof value ===number;
}));
});
或者,如果你知道字符串总是在第一个位置,你可以使用array.slice 这更有效:
var max = d3.max(array,function(array){
return d3.max(array.slice(1));
});
还有一种选择是使用一个访问函数返回 NaN $对于不是数字的值,c $ c>。这将导致d3.max忽略这些值。方便地,JavaScript的内置
Number
函数完全正是这样,所以你可以这样说:
var max = d3.max(array,function(array){
return d3.max(array,Number);
});
I want to find the maximum of a nested array, something like this:
a = [[1,2],[20,3]]
d3.max(d3.max(a)) // 20
but my array contains a text field that I want to discard:
a = [["yz",1,2],["xy",20,3]]
d3.max(a) // 20
If you have a nested array of numbers (arrays = [[1, 2], [20, 3]]
), nest d3.max:
var max = d3.max(arrays, function(array) {
return d3.max(array);
});
Or equivalently, use array.map:
var max = d3.max(arrays.map(function(array) {
return d3.max(array);
}));
If you want to ignore string values, you can use array.filter to ignore strings:
var max = d3.max(arrays, function(array) {
return d3.max(array.filter(function(value) {
return typeof value === "number";
}));
});
Alternatively, if you know the string is always in the first position, you could use array.slice which is a bit more efficient:
var max = d3.max(arrays, function(array) {
return d3.max(array.slice(1));
});
Yet another option is to use an accessor function which returns NaN
for values that are not numbers. This will cause d3.max to ignore those values. Conveniently, JavaScript's built-in Number
function does exactly this, so you can say:
var max = d3.max(arrays, function(array) {
return d3.max(array, Number);
});
这篇关于如何在javascript中查找嵌套数组的最大/最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!