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

214
Visualizações
Find max value of a duration field in format HH:MM:SS in Gatsby, Graphql

I have a JSON file in this format:

[
  {
    "id": 227,
    "duration": "02:52:58"
  },
  {
    "id": 226,
    "duration": "01:30:41"
  }
  ...
]

The duration field represents lengths of videos in HH:MM:SS format.

I need to find out the id that has the longest duration. I tried using sort and limit but that returns incorrect results.

// This doesn't work
(
  sort: { fields: [duration], order: DESC }
  limit: 1
)

What would be the best approach here?

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

0

The sorting you are trying to apply will only sort strings for their length, not by the value that contains (because GraphQL doesn't interpret it as dates or timestamps).

I think the easiest way is using that sorting in pure JavaScript.

Once you get the query working, the data will be stored inside props.data, so:

function convertDateObj(hhmmss){
    let date = new Date();

    let [hours, minutes, seconds] = hhmmss.split(':'); 

    date.setHours(+hours); // set the hours, using implicit type coercion
    date.setMinutes(minutes);
    date.setSeconds(seconds);

    return date;
}

const SomePage = ({ data }) => {
  let filteredData= data.someNode.edges.nodes.sort((a, b) => convertDateObj(a.duration) - convertDateObj(b.duration))

console.log(filteredData);

  return <div>Whatever</div>
}

Note: someNode will stand for your node, which has not been provided in your question. Change it accordingly. By default, this approach will sort it ascending. Change it to convertDateObj(b.duration) - convertDateObj(a.duration)) to make it descending

Other approaches with similar use-cases:

  • JavaScript seconds to time string with format hh:mm:ss
  • Array Sort by time hh:mm:ss

Thanks to @AKX for the suggestion. This would be more efficient and it will work either way:

function convertDateObj(hhmmss){   
    let [hours, minutes, seconds] = hhmmss.split(':'); 

    return hours * 60 * 24 + minutes * 60 + seconds;
}
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