headshot of Chris Tonkinson
Chris Tonkinson

tech {enthusiast, practitioner, leader, podcaster, mentor, entrepreneur}

HomeAboutTags



Refactored Podcast

I co-host Refactored, a casual, ongoing conversation between two technology leaders trying to suck a little less every day.

Career Schema Project

I founded the Career Schema Project with the mission of developing open standards and technology to reduce the hassle of online jobseeking.


RSS Subscribe

© 2024 Chris Tonkinson

groupsOf vs chunk in Underscore


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:

_.mixin

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

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] 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.