Recently while post-processing data from the Google Analytics API, I had the need to aggregate a set of records into subgroups. I needed a function to take an Array, source, and some grouping parameter, p and return the array divided into subarrays of length p.

source = [1, 2, 3, 4, 5, 6, 7, 8, 9]
p      = 3

grouping_func source, p
// => [
//      [1, 2, 3],
//      [4, 5, 6],
//      [7, 8, 9],
//    ]

Then what is grouping_func? My naive implementation, written as an Underscore mixin:


  groupsOf: (source, n) ->
    dest = []
    while source.length
      dest.push source.splice 0, n

No sooner had I integrated this into my code when I discovered the mind-bogglingly cool Underscore-contrib project. Turns out, the problem was already solved with the chunk function. From the documentation:

The _.chunk function, by default, accepts an array and a number and splits and returns a new array representing the original array split into some number of arrays of the given size:

_.chunk([0,1,2,3], 2);
//=> , [[0,1],[2,3]]

Great. Another wheel I reinvented unnecessarily. At least it turned me onto the Underscore-contrib project so it should be a net productivity gain.