Created
December 21, 2016 18:10
-
-
Save bflannery/c7fe052ada5f7a65a755260e489c13a1 to your computer and use it in GitHub Desktop.
Split an Array into X amount of SubArrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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