The following is my third attempt to complete the Chunky Monkey Algorithm problem.
The way I’m reading my code it seems like the for loop is not iterating over the final value in an array… however, this only seems to be the case when splice is being used. The problem pops up when chunkArrayInGroups([0, 1, 2, 3, 5, 6, 7], 2);
is called, values 0 - 6 are in neat arrays, however 7 seems to remain in the mutated array called by the for loop.
Can someone point out what aspect of splice()
or for loops
I seem to be misunderstanding. Thanks a million!
function chunkArrayInGroups(arr, size) {
let chunk = [];
for (let i = 0; i <= arr.length; i++){
function sizeLength(size){
if (arr.length >= size){
return size;
} else {
return arr.length;
}
}
let removed = arr.splice(0, sizeLength(size));
console.log('sizeLength(size):', sizeLength(size))
console.log('arr.length:', arr.length)
console.log('removed:', removed)
console.log('arr:', arr)
chunk.push(removed);
}
console.log(chunk);
return chunk;
}
chunkArrayInGroups([0, 1, 2, 3, 5, 6, 7], 2);
// chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
// chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:71.0) Gecko/20100101 Firefox/71.0
.
Challenge: Chunky Monkey
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey