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

Time:06-14

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.

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

CodePudding user response:

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)

  • Related