Skip to content

Instantly share code, notes, and snippets.

@timruffles
Last active October 8, 2015 19:18
Show Gist options
  • Save timruffles/3377784 to your computer and use it in GitHub Desktop.
Save timruffles/3377784 to your computer and use it in GitHub Desktop.
underscore chunk method
// Turns a list into a list of lists of specified lengths.
_.chunk = function(array,chunkSize) {
return _.reduce(array,function(reducer,item,index) {
reducer.current.push(item);
if(reducer.current.length === chunkSize || index + 1 === array.length) {
reducer.chunks.push(reducer.current);
reducer.current = [];
}
return reducer;
},{current:[],chunks: []}).chunks
};
// test
"chunk reduces an array to chunks": function() {
var chunked = _.chunk(["a","a","b","b","c"],2);
assert.equals(chunked[0],["a","a"]);
assert.equals(chunked[2],["c"]);
}
@olizilla
Copy link

Oh hai @timruffles. I just found myself doing the same thing for edutainment, and then stumbled on this here beauty!

We ended up with:

// i split an array into an array of arrays of size `chunk`
function chunk (array, size) {
  return array.reduce(function (res, item, index) {
    if (index % size === 0) { res.push([]); }
    res[res.length-1].push(item);
    return res;
  }, []);
}

...for other internet travellers who stumble here, you'll probably want something like: https://lodash.com/docs#chunk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment