Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js: Trying to sort ISO dates with respect to their duration

I’m trying to make a line chart using the chart.js library. I have an array that contains the ISO dates. I’m trying to check who makes ISO dates belong to the same hour and the same day. I would then use this information to create the line chart using the chart.js library.

For example, I have this array of ISO dates:

[
  { date: '2022-06-10T07:32:07.744Z' },
  { date: '2022-06-10T08:32:38.490Z' },
  { date: '2022-06-10T07:32:58.720Z' },
  { date: '2022-06-10T07:33:25.121Z' },
  { date: '2022-06-10T07:35:18.556Z' },
  { date: '2022-06-10T07:35:56.459Z' },
  { date: '2022-06-10T07:36:38.736Z' },
  { date: '2022-06-10T07:36:38.736Z' }
]

I want to know which ISO dates belong to the same hour and the same day from this array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m trying to make a line chart something like this – https://imgur.com/KuLqlD5.

>Solution :

You can use a bit of regex to just get the day and hour part and sort them with that.

const dates = [
  { date: '2022-06-10T07:32:07.744Z' },
  { date: '2022-06-10T08:32:38.490Z' },
  { date: '2022-06-10T07:32:58.720Z' },
  { date: '2022-06-10T07:33:25.121Z' },
  { date: '2022-06-10T07:35:18.556Z' },
  { date: '2022-06-10T07:35:56.459Z' },
  { date: '2022-06-10T07:36:38.736Z' },
  { date: '2022-06-10T07:36:38.736Z' }
]

// Regex to get day and hour
const hourAndDay = new RegExp('(\\d{1,2}T\\d{1,2})');

// Get unique day-hour pairs
const d = dates.map(y => hourAndDay.exec(y.date)[0])
const uniques = dates.filter((x, i) => d.indexOf(hourAndDay.exec(x.date)[0]) === i)

// Result object
const result = {};
uniques.forEach(x => result[hourAndDay.exec(x.date)[0]] = [])

// Sort based on hour and day
dates.forEach((x) => {
    const parsed = hourAndDay.exec(x.date)[0];
    result[parsed].push(parsed.split("T").map(Number))
})
console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading