I would like to get max values from subarrays in array1 array.
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].
console.log(Math.max(...one)); => Nan
I am not very well in JS, soo for any help I will be greatfull. 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.
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. If you have one item into the array, it will return array containing one element.
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
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));
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.