Chunk Monkey Challenge

Chunk Monkey Challenge
0.0 0

#1

I am struggling with the Chunk Monkey challenge (in the Basic Algorithm Scripting section).
My code is:

function chunkArrayInGroups(arr, size) {
  // Break it up. 
  var newArray = []; 
  var elementArray = [];
  var j;
  for (var i=0; i<arr.length; i++){
    j = i % size; 
    elementArray[j] = arr[i]; 
    if (j==(size-1) || i==(arr.length-1)){
     newArray.push(elementArray);
    } 
  }
  return newArray;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

I don’t know what wrong with that but result is [ [“c”,“d”],[“c”, “d”] while the right answer should be [ [“a”,“b”],[“c”,“d”]]. Could anyone help me. Thank you very much!


#2

I took your solution and add several console.log statements in so you could see what is happening to the different variables values while the code executes:

function chunkArrayInGroups(arr, size) {
  // Break it up. 
  var newArray = []; 
  var elementArray = [];
  var j;
  for (var i=0; i<arr.length; i++){
    console.log('i = ' + i);
    j = i % size; 
    
    console.log('j = ' + j);
    console.log('arr[' + i + '] = ' + JSON.stringify(arr[i]));
    elementArray[j] = arr[i]; 
    console.log('elementArray['+j+'] = ' + JSON.stringify(elementArray[j]));
    
    console.log('size-1 = ' + (size-1));
    console.log('arr.length-1 = ' + (arr.length-1));
    if (j==(size-1) || i==(arr.length-1)){
     console.log('if statement evaluates to true so push elementArray ( ' + JSON.stringify(elementArray) + ' ) into newArray');
     newArray.push(elementArray);
    } 
    console.log('newArray is ' + JSON.stringify(newArray));
    console.log(''); // blank lane separator
  }
  return newArray;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

The above yields the following:

i = 0
j = 0
arr[0] = "a"
elementArray[0] = "a"
size-1 = 1
arr.length-1 = 3
newArray is []

i = 1
j = 1
arr[1] = "b"
elementArray[1] = "b"
size-1 = 1
arr.length-1 = 3
if statement evaluates to true so push elementArray ( [“a”,“b”] ) into newArray
newArray is [[“a”,“b”]]

i = 2
j = 0
arr[2] = "c"
elementArray[0] = "c"
size-1 = 1
arr.length-1 = 3
newArray is [[“c”,“b”]]

i = 3
j = 1
arr[3] = "d"
elementArray[1] = "d"
size-1 = 1
arr.length-1 = 3
if statement evaluates to true so push elementArray ( [“c”,“d”] ) into newArray
newArray is [[“c”,“d”],[“c”,“d”]]

When you pushed elementArray into newArray, you were pushing a reference to what elementArray contains. So, whenever you modified elementArray later in the code, you were updating that reference. Since newArray contains two instances of the same array (elementArray), that is why you see the same subarray in both elements of the newArray.

To confirm what I have said above, you could add the following two lined after the for loop and before the return statement:

  elementArray[0] = 'Confused';
  elementArray[1] = 'yet?';

and the newArray would look like the following when it is returned:

[ [ ‘Confused’, ‘yet?’ ], [ ‘Confused’, ‘yet?’ ] ]