Created
July 23, 2020 15:08
-
-
Save nkint/1120843ad5292ac4fb4887c97b606332 to your computer and use it in GitHub Desktop.
Revisions
-
nkint created this gist
Jul 23, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,37 @@ 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)