Chunky Monkey Split does not seem to create array elements

Tell us what’s happening:

It looks like the array being passed, arr, is being split, but is not generating an array element. This is the output for the first iteration:

(4) [“a”, “b”, “c”, “d”]
VM31742:16 temp array = a,b
VM31742:18 new array = ,a,b
VM31742:16 temp array = c,d
VM31742:18 new array = ,c,d,c,d

Notice the console.log for arr? It shows the brackets around the entire array and the quotes around each element. In the console.log for tempArray, there are no brackets or quotes. So, I’m not sure why the split is not generating an array element.

Your code so far

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArray = [[]];
  var tempArray = [];
  for (var i=0;i<arr.length;i+=size) {
      console.log("temp array = " + tempArray);
      console.log("new array = " + newArray);
      tempArray.length = 0; 
  return newArray;

chunkArrayInGroups(["a", "b", "c", "d"], 2);

Your browser information:

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

Link to the challenge:

I removed the reference to newArray and removed the tempArray.length=0 line and all is good.

It isn’t showing the brackets in your console.log because you are concatenating it to a string. Change the + in the console.log to a ,.

See here.

Even if you remove the tempArray.length = 0, your code will not pass the tests, because in the example case of chunkArrayInGroups([“a”, “b”, “c”, “d”], 2); your function returns an array which looks like:

[ [], [ [ 'a', 'b' ], [ 'c', 'd' ] ],  [ [ 'a', 'b' ], [ 'c', 'd' ] ] ]

instead of:

[ [ 'a', 'b' ], [ 'c', 'd' ] ]

Why? You have two issues:

  1. You should not start newArray as an array with a blank array inside it. Instead newArray should be initialized as just a blank array.

  2. When you push elements into tempArray and then push tempArray into newArray, you are pushing a reference to tempArray’s values and not the actual values. See below for an example of what is happening when you push a reference to an array to another array.

var newArray = []; // starting with a blank array.
var tempArray = ['a','b'];
newArray.push(tempArray); // I pushed a reference to what is in tempArray and not the actual array ['a','b']
console.log(newArray); // displays [ ['a','b']] so everything seems OK
tempArray.push('c'); // I now added some new elements to tempArray
console.log(newArray);  // displays [ ['a', 'b', 'c'] ] because newArray contains a reference to tempArray's value which is now ['a', 'b', 'c'].