Skip to content

Instantly share code, notes, and snippets.

@midnite81
Last active June 21, 2020 00:36
Show Gist options
  • Save midnite81/b81274e84a821eefc5a4839a0f8ab231 to your computer and use it in GitHub Desktop.
Save midnite81/b81274e84a821eefc5a4839a0f8ab231 to your computer and use it in GitHub Desktop.
Javascript - split array into chunks
var myArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19, 20, 21];
function splitArray(array, numberOfChunks) {
arrayCount = array.length;
split = array.length / numberOfChunks;
chunks = [];
for(j = 0; j < numberOfChunks; j++) {
var chunk = [];
for(i = 0; i < split; i++) {
if (typeof array[i] !== 'undefined') {
chunk.push(array[i]);
}
}
array.splice(0, chunk.length);
chunks.push(chunk);
}
return chunks;
}
console.log(splitArray(myArray, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment