There are so many things wrong with my code (as per console.log).
-
This code:
console.log("This is end: " + size+i);
returns 20 instead of 2 when i = 0 and size = 2. -
Even weirder, this code:
arr1.push(arr.slice(i,size+i));
seems to know that size + i = 2 because the result from
console.log("This is arr1: " + arr1);
is the first 2 elements of the array.
So that’s really weird and is confusing.
My 2nd problem: Everytime I go through the loop, arr1
gets the next 2 (if size = 2
) elements added so by the time the loop is done, I end up with arr
= arr1
. So how do I save off the results of one slice so that it doesn’t get overwritten when the loop runs again?
Your code so far
// Attempt # 1
function chunkArrayInGroups(arr, size) {
// Break it up.
// console.log(arr.length, size);
var arr1 = [];
// Loop through original array to break it up into chunks using slice:
for (i=0; i<=arr.length; i = i+size){
console.log("This is array length: " + arr.length);
console.log("This is begin: " + i);
console.log("This is end: " + size+i);
console.log("This is array: " + arr);
console.log(arr.slice(i,size+i));
arr1.push(arr.slice(i,size+i));
console.log("This is arr1: " + arr1);
}
return arr1;
}
// chunkArrayInGroups(["a", "b", "c", "d"], 2);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/chunky-monkey