Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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);
about 4 years ago · Juan Pablo Isaza Relatório

0

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) 

about 4 years ago · Juan Pablo Isaza Relatório

0

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)));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda