Skip to content

Instantly share code, notes, and snippets.

@joePichardo
Created December 10, 2015 05:31
Show Gist options
  • Save joePichardo/05d2be09c1b52447d40a to your computer and use it in GitHub Desktop.
Save joePichardo/05d2be09c1b52447d40a to your computer and use it in GitHub Desktop.
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
// Bonfire: Chunky Monkey
// Author: @joepichardo
// Challenge: http://www.freecodecamp.com/challenges/bonfire-chunky-monkey
// Learn to Code at Free Code Camp (www.freecodecamp.com)
function chunk(arr, size) {
// Break it up.
//two empty arrays to make a two dimensional array
var outerArray = [];
var innerArray = [];
//go through the arr and push numbers to our innerArray
//(i+1) is used in the if statement since index and length are different by 1
//if there is a remainder of 0 or we reached the end of array length
//push this innerArray to our OuterArray, then empty the innerArray
// for the next loop
for(var i = 0; i < arr.length; i++){
innerArray.push(arr[i]);
if( (i+1) % size === 0 || i == arr.length-1){
outerArray.push(innerArray);
innerArray = [];
}
}
return outerArray;
}
chunk(["a", "b", "c", "d"], 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment