-2

so I have four arrays of different lengths. I'll call them one, two, three, four.

To find the longest, I put them in an array.

let length = [one.length, two.length, three.length, four.length];

so I get something like length = [10,54,22,4];

Math.max works find if I do Math.max(...length);

but I don't understand why Math.max([one.length,two.length,three.length,four.length]) returns NaN.

DecPK
  • 24,537
  • 6
  • 26
  • 42
duckets615
  • 45
  • 3
  • 2
    Math.max doesn't accept an array, just multiple arguments. That's what spread '...' does, turn an array into multiple arguments. – Alastair May 07 '21 at 08:35
  • Google "*Math.max NaN site:stackoverflow.com*" there are tens of duplicates. [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga May 07 '21 at 08:40

1 Answers1

2

Simply because Math.max() attempts to convert its arguments to numbers. An array does not convert into a number, so you get NaN.

Calling Math.max(...lengths) splits the lengths array into several arguments, which works (so long as they're all numbers, of course).

Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
AKX
  • 152,115
  • 15
  • 115
  • 172
  • So Math.max is trying to find the max number but the arrays themselves have yet to be converted by the .length method? so instead of Math.max([10,12,30,45]) it's something like Math.max([1,2,3], [21,7,9], [54, 60,11], [24,5,63]) which it can't do b/c they're still arrays and not numbers? – duckets615 May 07 '21 at 09:33