Skip to content

Instantly share code, notes, and snippets.

@jgatjens
Last active April 8, 2016 03:45
Show Gist options
  • Save jgatjens/3397ac8f9975d5ddf79f71419bc3b31c to your computer and use it in GitHub Desktop.
Save jgatjens/3397ac8f9975d5ddf79f71419bc3b31c to your computer and use it in GitHub Desktop.
Format object with loadash and reduce, format by day, formay by month, groupby and sum by dates.
/*
weekly = [
['3/6 - 3/12', 10],
['3/12 - 3/19', 13]
];
day = [
['3/6', 10]
['3/8', 2]
];
month = [
['jun', 10]
['feb', 2]
];
*/
// dateArray: [] of objects
// opt: String, 'day' or null to filter by month
function formatStepsBy(dateArray, opt) {
var filter = opt === 'day' ? 'M/D' : 'MMM';
return _.map(dateArray, function (item) {
var date = moment(item.date).format(filter);
return [date, item.steps];
});
}
function sum(arr, key, val){
return _.reduce(arr, function(result, item){
result[item[key]] = result[item[key]] || 0;
result[item[key]] += item[val];
return result;
}, {});
}
_.mixin({
sum: sum
});
function formatStepsWeekly(dateArray) {
var groupDates = _.map(dateArray, function (item) {
var groupBy = moment(item.date).startOf('isoweek').format('YYYY/MM/DD');
item.groupBy = groupBy;
return item;
});
var summed = _.sum(groupDates, 'groupBy', 'steps');
return _.map(summed, function (item, key) {
var start_date = moment(key).format('M/D');
var end_date = moment(key).add(7, 'day').format('M/D');
return [start_date +' '+ end_date, item];
});
}
var stepsData = [
{
"date": "2016-03-01",
"points": 394.4,
"steps": 3650,
"calories": 1687.4735,
"activityCalories": 412.3124,
"distance": 1.18
},
{
"date": "2016-03-08",
"points": 459.6,
"steps": 4330,
"calories": 1707.8484,
"activityCalories": 412.3124,
"distance": 1.3982
},
{
"date": "2016-03-012",
"points": 430.4,
"steps": 4022,
"calories": 1698.7234,
"activityCalories": 412.3124,
"distance": 1.2988
},
{
"date": "2016-03-22",
"points": 376,
"steps": 3514,
"calories": 1681.7235,
"activityCalories": 412.3124,
"distance": 1.1429
}
];
console.log(formatStepsBy(stepsData, 'day'));
console.log(formatStepsBy(stepsData));
console.log(formatStepsWeekly(stepsData));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment