[英]max value from subarray
I would like to get max values from subarrays in array1 array. 我想从array1数组的子数组中获取最大值。
var array1 = [[4, 2, 7, 1], [20, 70, 40, 90], [1, 2, 0]];
let one = array1.slice(0,1);
let two = array1.slice(1,2);
let three = array1.slice(2,3);
console.log(one);
console.log(two);
console.log(three);
in result I had: 结果我有:
> Array [Array [4, 2, 7, 1]]
> Array [Array [20, 70, 40, 90]]
> Array [Array [1, 2, 0]]
Then I tried to get max values from one, two, and three variables but always is an error [NaN]. 然后,我尝试从一个,两个和三个变量中获取最大值,但始终是一个错误[NaN]。
console.log(Math.max(...one)); => Nan
I am not very well in JS, soo for any help I will be greatfull. 我对JS不太好,如果能提供任何帮助,我都会非常高兴。 Thanks
谢谢
You can try with map
function and for each sub array call Math.max
which will return a single value for a sub array. 您可以尝试使用
map
函数,并为每个子数组调用Math.max
,这将为子数组返回单个值。
const array1 = [[4, 2, 7, 1], [20, 70, 40, 90], [1, 2, 0]]; const maxValues = array1.map(item => Math.max(...item)); console.log(maxValues);
slice
function returns another array. slice
函数返回另一个数组。 If you have one item into the array, it will return array containing one element. 如果数组中有一项,它将返回包含一个元素的数组。
console.log(Math.max(...one));
console.log(Math.max(... one)); => Nan
=>南
Because slice
returns the array from the input array (ie one
is a 2d array ), you need to get the 0th index 由于
slice
从输入数组返回数组(即one
是2d数组 ),因此您需要获取第0个索引
let one = array1.slice(0,1)[0];
Similarly 相似地
let two = array1.slice(1,2)[0];
let three = array1.slice(2,3)[0];
Now console.log(Math.max(...one));
现在
console.log(Math.max(...one));
will give you correct value 会给你正确的价值
For getting max from all arrays, try 要从所有数组中获取最大值,请尝试
console.log(Math.max(...one,...two,...three)); //spread with comma
For getting individual arrays 为了获得单个阵列
console.log(array1.map( s => Math.max.apply(null, s));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.