Chunky Monkey Loop Help

Chunky Monkey Loop Help
0

#1

Tell us what’s happening:
Alright…I am stuck. When I console.log my code, it appears that test 3,4,5,6 (in the list of tests) are not looping through all the way. The other tests pass. I have worked out the code manually on paper and do not see why this is happening.

For example, the second to last test passes [0, 1, 2, 3, 4, 5, 6, 7, 8] as the first argument, and 4 as the second argument. It should return [0, 1, 2, 3], [4, 5, 6, 7], [8]. But I am getting [0,1,2,3,],[4,5,6,7][] with just an empty array at the end.

Any ideas as to what is happening is appreciated!

Thanks,
David

Your code so far

function chunkArrayInGroups(arr, size) {
  
  var newArray = [];
  var startCut = 0;
  var endCut = size;
                
  
  for (i = 0; i < arr.length/size; i++) {
    newArray.push(arr.slice(startCut, endCut));
     startCut = startCut + size;
     endCut = size + size;
      } 
  

console.log(newArray);
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.88 Safari/537.36.

Link to the challenge:


#2

i < arr.length/size
How might this be a problem? What does it do?


#3

My intention with that was to have it iterate through the loop he correct number of times based on the output I needed. Is this where my problem is? My thought process was this:

1st Test: arr.length is 4, size argument is 2 - the desired output has 2 sub arrays.
2nd Test: arr.length is 6, size argument is 3, desired output has 2 sub arrays.


#4

I have edited your original code by putting console.log statement in at various points to see the values of certain values during the for loop iteration.

function chunkArrayInGroups(arr, size) {
	var newArray = [];
	var startCut = 0;
	var endCut = size;

	for (i = 0; i < arr.length / size; i++) {
	  console.log('i = '+i);
		newArray.push(arr.slice(startCut, endCut));
		console.log('newArray = ' + JSON.stringify(newArray));
		startCut = startCut + size;
		console.log('startCut = ' + startCut);
		endCut = size + size;
		console.log('endCut = ' + endCut)
		console.log(); // blank line separator
	}
	console.log(newArray);
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);

When the above code executes, you will see the following in the browser’s console (Ctrl+Shft+J in Chrome):

i = 0
newArray = [[0,1]]
startCut = 2
endCut = 4

i = 1
newArray = [[0,1],[2,3]]
startCut = 4
endCut = 4

i = 2
newArray = [[0,1],[2,3],[]]
startCut = 6
endCut = 4

i = 3
newArray = [[0,1],[2,3],[],[]]
startCut = 8
endCut = 4

i = 4
newArray = [[0,1],[2,3],[],[],[]]
startCut = 10
endCut = 4

[ [ 0, 1 ], [ 2, 3 ], [], [], [] ]

This should provide some insight for you as to why your code is not returning the correct array.