Last Updated: February 25, 2016
·
1.109K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside