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

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

Answers:

Answer

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.

Answer

console.log(Math.max(...one)); => 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];

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.