Skip to content

Instantly share code, notes, and snippets.

@sebshub
Created December 2, 2016 22:06
Show Gist options
  • Save sebshub/f571908b969cc329b1179f6cbd59d1cc to your computer and use it in GitHub Desktop.
Save sebshub/f571908b969cc329b1179f6cbd59d1cc to your computer and use it in GitHub Desktop.
Chunky Monkey FCC freecodecamp exercise 3 solutions
function chunkArrayInGroups(arr, size) {
// first solution
/*var arr1 = [];
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
if (i % size !== size - 1)
arr1.push(arr[i]);
else {
arr1.push(arr[i]);
arr2.push(arr1);
}
}
if (arr1 !== 0)
arr2.push(arr1);
return arr2;
}*/
// second solution
/*arr = arr.slice();
var finalAnswer = [];
for (var i = 0, lenGth = arr.length; i < lenGth; i+=size) {
finalAnswer.push(arr.slice(0, size));
arr = arr.slice(size);
}
return finalAnswer;
}*/
// 3 solution
var newArr = [];
var i = 0;
while (i < arr.length) {
newArr.push(arr.slice(i, i + size));
i += size;
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
@sebshub
Copy link
Author

sebshub commented Dec 2, 2016

Chunky Monkey freecodecamp.com Exercise 3 solutions
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment