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

364
Visualizações
JavaScript: sort an array of timestamps with day–month–year format

I have an array of timestamps or strings that are of this format - day–month–year. e.g ['03-11-2018', '04-12-2018', '10-01-2017', '10-12-2017']

And I want to sort them chronologically so the above array would become [ '10-01-2017', '10-12-2017', '03-11-2018', '04-12-2018' ]

I am aware that you can use moment.js to do this but I want to write this by hand without using any 3rd lib.

Here is my attempt:

function sortTimestamp(array) {
  array.sort((time1, time2) => {
    const [day1, month1, year1] = time1.split('-')
    const [day2, month2, year2] = time2.split('-')
    return year2 > year1
      ? -1
      : year2 < year1
      ? 1
      : month2 > month1
      ? -1
      : month2 > month1
      ? 1
      : day2 > day1
      ? -1
      : 1
  })
}

It works ok but it is not really readable and it is a very imperative approach. I wonder if there is a better way to do it and also ideally it can be extended to support that other date formats e.g. month–day–year.

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

0

An alternative is to specify with extra arguments what the format is (regex) and how it should be reordered to ISO-style YYYYMMDD format. Then the function can perform that replacement and do a lexical sort:

function sortTime(array, regex, iso) {
    let fmt = time => time.replace(regex, iso);
    return array.sort((time1, time2) => 
        fmt(time1).localeCompare(fmt(time2)));
}

// demo
let dates = ['03-11-2018', '04-12-2018', '10-01-2017', '10-12-2017'];
let result = sortTime(dates, /(..)-(..)-(....)/, "$3$2$1");
console.log(result);

So if the input should be interpreted as mm-dd-yyyy instead of dd-mm-yyyy, then make the third argument "$3$1$2" instead of "$3$2$1".

about 4 years ago · Juan Pablo Isaza Relatório

0

It's a little simpler using subtraction rather than nested ternaries.

function sortTimestamp(array) {
  array.sort((time1, time2) => {
    const [day1, month1, year1] = time1.split('-')
    const [day2, month2, year2] = time2.split('-')
    return year1 - year2 || month1 - month2 || day1 - day2;
  })
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can first convert them to Date objects then use the getTime functionality to compare for sorting. A similar question was answered here

const dates = ['03-11-2018', '04-12-2018', '10-01-2017', '10-21-2017']

sortedDates = dates.sort((a,b)=>{
  const dateA = new Date(a)
  const dateB = new Date(b)
  //change the comparison sign for required orde
  return dateA.getTime() < dateB.getTime() 
  ? 1 
  : -1
 
})
console.log(sortedDates)

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