Skip to content

Instantly share code, notes, and snippets.

@danawoodman
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danawoodman/c0fdec772dbffcf3dfa4 to your computer and use it in GitHub Desktop.
Save danawoodman/c0fdec772dbffcf3dfa4 to your computer and use it in GitHub Desktop.
Group and sum range of hours by the hour
var _ = require('lodash');
var ranges = [
["12:00", 0.0], ["12:15", 0.0], ["12:30", 0.0], ["12:45", 0.0],
["01:00", 0.0], ["01:15", 0.0], ["01:30", 0.0], ["01:45", 0.0],
["02:00", 0.0], ["02:15", 0.0], ["02:30", 0.0], ["02:45", 0.0],
["03:00", 0.0], ["03:15", 0.0], ["03:30", 0.0], ["03:45", 0.0],
["04:00", 0.0], ["04:15", 0.0], ["04:30", 0.0], ["04:45", 0.0],
["05:00", 0.0], ["05:15", 0.0], ["05:30", 0.0], ["05:45", 0.0],
["06:00", 0.0], ["06:15", 0.0], ["06:30", 0.0], ["06:45", 0.0],
["07:00", 10.0], ["07:15", 328.0], ["07:30", 1249.0], ["07:45", 2554.0],
["08:00", 3947.0], ["08:15", 5263.0], ["08:30", 6431.0], ["08:45", 6861.0],
["09:00", 6904.0], ["09:15", 7006.0], ["09:30", 7046.0], ["09:45", 6909.0]
];
var result = {};
_.forEach(ranges, function (n, index) {
// Get the whole hour from the hour log.
var key = n[0].split(':')[0];
// The number of hours for the given log.
var val = n[1];
// Set or incriment the hour total.
result[key] ?
result[key] += val :
result[key] = val;
});
/*
Result:
{ '12': 0,
'01': 0,
'02': 0,
'03': 0,
'04': 0,
'05': 0,
'06': 0,
'07': 4141,
'08': 22502,
'09': 27865 }
*/
// Turn the result into an array of arrays.
var result = _.zip(_.keys(result), _.values(result));
console.log(result);
/*
Result:
[ [ '12', 0 ],
[ '01', 0 ],
[ '02', 0 ],
[ '03', 0 ],
[ '04', 0 ],
[ '05', 0 ],
[ '06', 0 ],
[ '07', 4141 ],
[ '08', 22502 ],
[ '09', 27865 ] ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment