Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const howManyMonthsBetween = (from, to) => {
- const fromDate = new Date(from)
- const toDate = new Date(to)
- const yearsBetween = toDate.getFullYear() - fromDate.getFullYear()
- return (yearsBetween * 12) + toDate.getMonth() - fromDate.getMonth()
- }
- const useCreateDataArray = (results) => {
- // sort array from earliest to latest
- const chronological = results.sort((a, b) => {
- return a.datetime > b.datetime
- })
- const earliestEntryDate = new Date(chronological[0].datetime)
- const latestEntryDate = new Date(chronological[chronological.length - 1].datetime)
- const monthsBetween = howManyMonthsBetween(earliestEntryDate, latestEntryDate)
- // create object where:
- // keys: every possible month (in ms since 1970) from earliest to latest entries
- // values: how many reports occurred in that month (initialized to 0)
- const initDataSeriesObj = Object.fromEntries(
- [...Array(monthsBetween)].map((_, idx) => {
- return [new Date(
- earliestEntryDate.getFullYear(),
- earliestEntryDate.getMonth() + idx,
- 1
- ).getTime(), 0]
- })
- )
- const dataSeriesObj = chronological.reduce((acc, val) => {
- const valAsDate = new Date(val.datetime)
- const nearestMonth = new Date(valAsDate.getFullYear(), valAsDate.getMonth(), 1).getTime()
- acc[nearestMonth]++
- return acc
- }, initDataSeriesObj)
- // return Object.entries(dataSeriesObj)
- return Object.keys(dataSeriesObj).map((k) => [Number(k), dataSeriesObj[k]])
- }
- export default useCreateDataArray
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement