'How to get Max Date in an array?

I'm trying to get max day in an array of dates but it returns Invalid Date or null. Can't figure out what is wrong. Should I convert the values to another format? Any help will be appreciated.

const dates=[
    '2022-10-13T00:00:00.000',
     '2023-10-14T00:00:00.000', 
     '2024-10-15T00:00:00.000', 
     '2020-10-16T00:00:00.000', 
     '2015-10-17T00:00:00.000', 
     '2028-10-18T00:00:00.000', 
     '2010-10-19T00:00:00.000', 
    ]
//const maxDate=new Date(Math.max.apply(null,dates));

const maxDate=new Date(
      Math.max(
        ...dates
      ),
    )
    
    console.log('maxDate', maxDate)


Solution 1:[1]

you can do the following:

const dates = [
"2022-10-13T00:00:00.000",
"2023-10-14T00:00:00.000",
"2024-10-15T00:00:00.000",
"2020-10-16T00:00:00.000",
"2015-10-17T00:00:00.000",
"2028-10-18T00:00:00.000",
"2010-10-19T00:00:00.000",
];
const datesArray = dates.map((element) => new Date(element));

const maxDate = new Date(Math.max(...datesArray));

console.log("maxDate", maxDate);

Solution 2:[2]

Context

Math.max takes the following arguments (from docs):

value1, value2, ... , valueN
Zero or more numbers among which the largest value will be selected and returned.

That means if you pass it a non-empty array (like your array of strings), it will return NaN.

Creating a new Date() with NaN as an argument results in an Invalid Date.

Solution

Instead of comparing strings, you could compare the dates, or its Unix timestamps.

So given your example, all you need to do is make dates from those strings:

const dates = [
  new Date("2022-10-13T00:00:00.000"),
  new Date("2023-10-14T00:00:00.000"),
  new Date("2024-10-15T00:00:00.000"),
  new Date("2020-10-16T00:00:00.000"),
  new Date("2015-10-17T00:00:00.000"),
  new Date("2028-10-18T00:00:00.000"),
  new Date("2010-10-19T00:00:00.000"),
];

const latestDate = new Date(Math.max(...dates))

console.log('latestDate', latestDate) 

Solution 3:[3]

The issue with your current code is that dates is an array of strings. Since Math.max() only works with numbers each of the arguments is converted to a number.

Math.max("1", "3", "2") //=> 3

The issue with a date string is that converting it to a number produces NaN.

const date = "2022-10-13T00:00:00.000";
+date //=> NaN

This will result in Math.max() also returning NaN. In turn new Date(NaN) will produce an "invalid date".


To fix your issue you first have to convert your array of date strings into an array of numbers. The easiest way to do this is to convert them to timestamps by passing each string into Date.parse().

You can then spread the array of timestamps into Math.max() and get the highest timestamp. You can then pass the timestamp to the Date constructor to produce a date.

const dates = [
  '2022-10-13T00:00:00.000',
  '2023-10-14T00:00:00.000', 
  '2024-10-15T00:00:00.000', 
  '2020-10-16T00:00:00.000', 
  '2015-10-17T00:00:00.000', 
  '2028-10-18T00:00:00.000', 
  '2010-10-19T00:00:00.000', 
];

const timestamps = dates.map(Date.parse);
const maxTimestamp = Math.max(...timestamps);
const maxDate = new Date(maxTimestamp);

console.log({ maxDate });

Alternatively you can combine the above steps together in a one-liner.

const maxDate = new Date(Math.max(...dates.map(Date.parse)));

Solution 4:[4]

If you log the outcome of this particular code:

Math.max(
   ...dates
),

you will get a NaN as result. It's because Math.max only expects numbers to work with. You instead passed a bunch a strings. You need to parse those strings to numbers first. Since you're handling dates it's best using Date.parse for this. Everything else can stay the same. This is how it can look like:

const dates = [
  '2022-10-13T00:00:00.000',
  '2023-10-14T00:00:00.000', 
  '2024-10-15T00:00:00.000', 
  '2020-10-16T00:00:00.000', 
  '2015-10-17T00:00:00.000', 
  '2028-10-18T00:00:00.000', 
  '2010-10-19T00:00:00.000', 
];

const maxDate = new Date(
  Math.max(
    ...dates.map(date => Date.parse(date))
  ),
);

console.log('maxDate:', maxDate);

Since clean, thus maintainable code is important too I even would suggest writing it like this:

const dates = [
  '2022-10-13T00:00:00.000',
  '2023-10-14T00:00:00.000', 
  '2024-10-15T00:00:00.000', 
  '2020-10-16T00:00:00.000', 
  '2015-10-17T00:00:00.000', 
  '2028-10-18T00:00:00.000', 
  '2010-10-19T00:00:00.000', 
];

const datesInMiliseconds = dates.map(date => Date.parse(date));
const maxMiliseconds = Math.max(...datesInMiliseconds);
const maxDate = new Date(maxMiliseconds);

console.log('maxDate:', maxDate);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Katherine R
Solution 2 Webber
Solution 3 3limin4t0r
Solution 4 MoonByteShaker