Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!