fbyx7a
Last Updated: February 25, 2016
·
518
· stpe

Use reduce() to get sum of interval of array of values

One, pretty neat, way of getting the sum of a given interval of an array of values. Useful among other things when doing graphs, e.g. when you want to plot the accumulative value every 5 minutes instead of the value for each individual minute.

var INTERVAL = 5;
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

list.reduce(function(result, value, index) {
  var i = Math.floor(index/INTERVAL);
  result[i] ? result[i] += value : result[i] = value;
  return result;
}, []);

// Output: [15, 40, 11]

Also available as a gist.