如何在javascript中找到嵌套数组的最大值/最小值? [英] How to find the max/min of a nested array in javascript?
问题描述
我想找到嵌套数组的最大值,如下所示:
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
推荐答案
如果你有一个嵌套的数字数组 (arrays = [[1, 2], [20, 3]]
),嵌套 d3.max:
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);
});
或者等效地,使用 array.map:
var max = d3.max(arrays.map(function(array) {
return d3.max(array);
}));
如果你想忽略字符串值,你可以使用 array.filter忽略字符串:
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";
}));
});
或者,如果您知道字符串总是在第一个位置,您可以使用 array.slice 效率更高一点:
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));
});
另一种选择是使用访问器函数,该函数为不是数字的值返回 NaN
.这将导致 d3.max 忽略这些值.方便的是,JavaScript 的内置 Number
函数正是这样做的,所以你可以说:
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屋!