Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Split an array into an array of arrays of a specific length. Source: http://stackoverflow.com/questions/8495687/split-array-into-chunks/10456644#10456644
// Prototype method
Array.prototype.chunk = function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
};
//
// Demo
// [1,2,3,4,5,6,7].chunk(3);
//
// Outputs:
// [
// [1,2,3],
// [4,5,6],
// [7]
// ]
//Function method
var splitArray = function(array, chunkSize) {
return [].concat.apply(
[],
array.map(function(elem, i) {
return i%chunkSize ? [] : [array.slice(i, i+chunkSize)];
})
);
};
//
// Demo
// splitArray([1,2,3,4,5,6,7], 7);
//
// Outputs:
// [
// [1,2,3],
// [4,5,6],
// [7]
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment