Skip to content

Instantly share code, notes, and snippets.

@nkint
Created July 23, 2020 15:08
Show Gist options
  • Save nkint/1120843ad5292ac4fb4887c97b606332 to your computer and use it in GitHub Desktop.
Save nkint/1120843ad5292ac4fb4887c97b606332 to your computer and use it in GitHub Desktop.
Dayjs group by time-range
var dayjs = require('dayjs')
var minMax = require('dayjs/plugin/minMax')
dayjs.extend(minMax)
const input = [
{time: '2020-07-23T11:30:00Z', value: 1},
{time: '2020-07-24T11:30:00Z', value: 1},
{time: '2020-07-05T11:30:00Z', value: 2},
{time: '2020-07-30T11:30:00Z', value: 3},
]
const param = 'week'
const times = input.map(x => dayjs(x.time))
const min = dayjs.min(times)
const max = dayjs.max(times)
const start = min.startOf(param)
const size = max.startOf(param).diff(start, param)
const ranges = new Array(size + 1)
.fill(0)
.map((_, i) => start.add(i, param))
const toString = (x) => dayjs(x).startOf(param).format('YYYY MM DD')
const dict = ranges.reduce((acc, x) => {
const stringFormat = toString(x)
acc[stringFormat] = []
return acc
}, {})
const grouped = input.reduce((acc, x) => {
const stringFormat = toString(x.time)
dict[stringFormat].push(x)
return acc
}, dict)
const average = array => array.reduce((acc, x) => acc + x.value, 0) / (array.length || 1)
const result = Object.fromEntries(Object.entries(grouped).map(([key, value]) => [key, average(value)]))
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment