I am looking for a max number in each subarrays of an array. But when I did that it give me NaN. Why?
Let me outline what I've found. For context, I perform these tests in the console of Google Chrome.
Original array:
let arr = [[4, 5, 1, 3], [13, 27, 18, 26]];
I slice out the 1st subarray and assigned to arr1.
let arr1 = arr.slice(0, 1);
arr1;
[4, 5, 1, 3]
arr1[0]; //this is to see if I can get value at index 0
[4, 5, 1, 3]
arr1.length;
1
When I perform the Math.max on arr1, I get NaN.
Math.max(...arr1);
NaN
When I couldn't get the Math.max value, I thought arr1 wasn't an array so I test to see if it is an array:
Array.isArray(arr1)
true
I was able to get the max number from the subarray using the original arry. My question is why I cannot get the Math.max on arr1, the array that sliced out of the original?
CodePudding user response:
arr1
is an array of arrays, not an array of numbers. You can flatten the array before using Math.max
. (Note: if you just want the i
th subarray, just use arr[i]
instead of slice
. slice
is only useful when you want multiple consecutive elements from an array.)
let arr = [[4, 5, 1, 3], [13, 27, 18, 26]];
let arr1 = arr.slice(0, 1);
console.log(JSON.stringify(arr1));
let max = Math.max(...arr1.flat());
console.log(max);
CodePudding user response:
Your arr1
isn't [4, 5, 1, 3]
, it's [[4, 5, 1, 3]]
— an array containing a single element, which is an array of numbers. slice
creates an array containing the elements you've selected from the original array (just the first one in your case). That first element in arr
is an array, so you end up with an array containing that array.
If you want to use arr1
as you've shown, just use arr[0]
, not arr.slice(0, 1)
:
let arr = [[4, 5, 1, 3], [13, 27, 18, 26]];
let arr1 = arr[0];
console.log(Math.max(...arr1));