At the end of function, i get with debug console.log messed up array, but yet can't find a way to fix it, please read my short code

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var multiArr = [];



  var betaArray = [];
  betaArray.push(arr[0]);
  for ( var i = 1; i<arr.length;i++ ){


    if ( i % size === 0 ){

        multiArr.push(betaArray);
        betaArray.length = 0;

    }

    betaArray.push(arr[i]);

  }

  if ( betaArray.length !== 0 )
    multiArr.push(betaArray);
  console.log(multiArr);  return multiArr;
}

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

So why with console.log i get "c","d","c","d"
This challange: https://www.freecodecamp.com/challenges/chunky-monkey

part of your problem is that when you push betaArray onto multiArr, you are passing the actual object, so when you reset betaArray.length to 0, it changes it in multiArray too.

What you want to do is put the values from betaArray in multiArray. There are various ways to do it, but Iā€™d take a look at the Array.slice() method.

1 Like