max value from subarray

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);




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(; => 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 = => Math.max(...item));


slice function returns another array. If you have one item into the array, it will return array containing one element.


console.log(Math.max(; => Nan

Because slice returns the array from the input array (i.e. one is a 2d array), you need to get the 0th index

let one = array1.slice(0,1)[0];


let two = array1.slice(1,2)[0];
let three = array1.slice(2,3)[0];

Now console.log(Math.max(; will give you correct value

For getting max from all arrays, try

console.log(Math.max(,...two,...three)); //spread with comma

For getting individual arrays

console.log( s => Math.max.apply(null, s)); 


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.