2

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?

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
redstuck
  • 43
  • 4
  • Please @redstuck comment on the resolution instead of opening new posts. Upvote/Downvote/accept answers and give some feedback – Ferran Buireu Oct 03 '21 at 09:53

1 Answers1

1

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:


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;
}
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67