Skip to content

Instantly share code, notes, and snippets.

@dannycroft
Created November 25, 2013 19:28
Show Gist options
  • Save dannycroft/7647231 to your computer and use it in GitHub Desktop.
Save dannycroft/7647231 to your computer and use it in GitHub Desktop.
Lodash / Underscore method for breaking data sets into smaller sets (chunks)
/**
* Lodash / Underscore method for breaking data sets into smaller sets (chunks)
*
* @arguments
*
* collection: Array / Object
* chuckSize: Number
*
* @example
*
* -> _.chunk(["number","array_element","city_prefix","city_suffix","street_suffix"], 3));
* -> [["number","array_element","city_prefix"], ["city_suffix","street_suffix"]]
*/
_.mixin({
'chunk': function (collection, chunkSize) {
if (!collection || _.isNaN(parseInt(chunkSize, 10))) { return [];}
return _.toArray(_.groupBy(collection, function (iterator, index) {
return Math.floor(index / parseInt(chunkSize, 10));
}));
}
});
@ezhlobo
Copy link

ezhlobo commented Aug 31, 2016

The iteratee is invoked with one argument: (value)
@ https://lodash.com/docs#groupBy

That is why I think this method doesn't work for me.

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