7

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
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

21

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
  • 6,173
  • 2
  • 24
  • 43
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 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