Skip to content

Instantly share code, notes, and snippets.

@bflannery
Created December 21, 2016 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bflannery/c7fe052ada5f7a65a755260e489c13a1 to your computer and use it in GitHub Desktop.
Save bflannery/c7fe052ada5f7a65a755260e489c13a1 to your computer and use it in GitHub Desktop.
Split an Array into X amount of SubArrays
// Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
function chunkArrayInGroups(arr, size) {
let tempArr = [];
let newArr = [];
for(i=0; i <arr.length; i++) {
if( i % size !== size-1)
tempArr.push(arr[i]);
else {
tempArr.push(arr[i]);
newArr.push(tempArr);
tempArr=[];
}
}
if(tempArr.length !==0)
newArr.push(tempArr);
return newArr;
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment