Skip to content

Instantly share code, notes, and snippets.

@vwochnik
Created April 12, 2016 11:42
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 vwochnik/899ce8caf485a4f0d68ff6966fc6307d to your computer and use it in GitHub Desktop.
Save vwochnik/899ce8caf485a4f0d68ff6966fc6307d to your computer and use it in GitHub Desktop.
Aggregate dataset by ticks
/**
* Aggregates a dataset containing {x,y} values by an array of x-axis ticks
* where the aggregated dataset contains one {x,y} value per specified
* tick.
* @param dataset input dataset of {x,y} values
* @param ticks array of ticks to aggregate by
* @return new dataset containing aggregated {x,y} values
*/
function aggregate(dataset, ticks) {
return _.chain(dataset)
.filter(function(data) {
return (data.x >= ticks[0] && data.x < ticks[ticks.length - 1]);
})
.groupBy(function(data) {
for (var i = 0; i < ticks.length; i++) {
if (data.x < ticks[i]) {
return i - 1;
}
}
return ticks.length - 1;
})
.map(function(group, i) {
return _.reduce(group, function(memo, data) {
memo.y += data.y;
return memo;
}, { x: ticks[i], y: 0 });
}).value();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment