5

I'm trying to create a piece of code in Javascript that compares an array of Epoch times (which are just large integers) and I want it to find the smallest, or most historic, time value.

This is what I've written so far but it just returns 'NaN' when I run it.

var times = [1501502460000,1501497900000,1501498920000,1501493700000];
lowestTime = Math.min(times);

Note that I am using the Math.min() not Math.max().

Cœur
  • 34,719
  • 24
  • 185
  • 251

1 Answers1

15

If you want Math.min() to process an array of values, you have to use .apply():

var lowestTime = Math.min.apply(Math, times);

You could also use the new-ish spread syntax:

var lowestTime = Math.min(... times);

but that doesn't work in all environments.

When you pass the array directly, the first thing Math.min() does is try to convert it to a number because that's what it expects: individual numbers. When that happens, through a round-about process the resulting value will be NaN.

Jens
  • 5,853
  • 1
  • 22
  • 41
Pointy
  • 389,373
  • 58
  • 564
  • 602
  • 2
    It should be noted that the reason that you must do this is because `Math.min` does not take an array as a parameter. It takes a comma separated list of n parameters, which is why `.apply()` and `...` work - they convert an array to a comma separated list of values. – mhodges Jul 31 '17 at 17:15