Chunky Monkey (under Basic Algorithm Scripting) question

Hi, I manage to complete this challenge but I didn’t manage to use the array.push() method. I have included my code below :

/** setup

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

if (arr.length/size <= 2) {
firstArr= arr.splice (0, size);
secondArr= arr;
totalArr = [firstArr, secondArr];
}

else if (arr.length/size <= 3) {
firstArr= arr.splice (0, size);
secondArr= arr.splice (0,size);
thirdArr = arr;
totalArr = [firstArr, secondArr, thirdArr]; }

else if (arr.length/size <= 4) {
firstArr= arr.splice (0, size);
secondArr= arr.splice (0,size);
thirdArr = arr.splice(0,size);
fourthArr= arr;
totalArr = [firstArr, secondArr, thirdArr, arr]; }

return totalArr;

}

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

**/ end setup

I feel like my code is not complete because if chunkArrayInGroups ([0, 1, 2, 3, 4, 5], 1), the result is only [].

Can anyone push me to the right direction to produce a better code for this challenge?

Many thanks in advance :slight_smile:

Why do you want to avoid array.push()? Your method cannot scale up.

What is any number divided by 1 equal to? You don’t have an else case to handle that. So it’s just passing you the empty array.

But as @soarer alluded, doing it this way will only solve as many test cases as you are able to think ahead to hard code in.

Yea, I know that. It’s just that I can’t seem to find a way to use array.push() in my code.

I’m stuck on this one as well. But I think you would want totalArr = [firstArr, secondArr];
to be where you have the array.push().

Hi guys I wanted to share my solution. I used the splice method to split the array based on the size given and then push the spliced Array into a completely newArray. Tell me what you think.:slight_smile:

function chunkArrayInGroups(arr, size) {

var arraySize  = arr.length/size;

var newArray = [];

    for (var i = 0; i < arraySize ; i++){

        var subArray= arr.splice(0,size);

        newArray.push(subArray);

    }

return newArray;

}`
15 Likes

@TTomaszito That looks pretty good, another option is to remember than for loops don’t need to increment by one:

function chunkArrayInGroups(arr, size) {
// Break it up.
var chunkArr = [];
for (var i=0; i < arr.length; i += size){
chunkArr = chunkArr.concat(Array.of(arr.slice(i, i + size)));
}
return chunkArr;

}

6 Likes

@ChadKreutzer that’s interesting I never thought about other increments. Makes loads of sense thanks for the tip.

Great solution TTomaszito!

If you want to force yourself to use “.slice” instead of “.splice” here is what you can do:

chunkArr.push(arr.slice(i*size+0, size*i+size));

1 Like

hey i did this dont know if the correct approach though(scalable)

function chunkArrayInGroups(arr, size) {
var multiD = [];

arr.map(function(element,index){
if(index % size === 0){
multiD.push(arr.slice(index,size+index));

}

});
//console.log(multiD);

return multiD;
}

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

1 Like

I can see these posts are months old. I’m just starting through algorithms and using the forum to see better solutions (there is always more than one!)

thought a bit of refactoring will help to do away with concat & Array.of (and to bring in push)… since slice returns an array, using push will get us a two dimensional…

function chunkArrayInGroups(arr, size) {
// Break it up.
var chunkArr=[];
for(var index=0;index<arr.length;index+=size)
chunkArr.push(arr.slice(index,index+size));
return chunkArr;
}

5 Likes

Good job getting past the challenge. :thumbsup:

Here is my code:


function chunkArrayInGroups(arr, size) {
  // An array to store the results
  results = [];
  // Divide the length of 'arr' by 'size' and 'ceil' it off to next number. 'round' is different from 'ceil'
  count = Math.ceil(arr.length/size);
  
  for (var i=0; i<count; i++){
  	// Push the sliced array to 'results'
  	results.push(arr.slice(0, size));
  	// Remove the sliced elements from the array and keep the rest
  	arr = arr.slice(size, arr.length);
  }
  return results;
}
1 Like

Here is my code in case you are curious, this took some trial and error but I finally got it. My first solution had a FOR loop and extra function, I wanted to clean it up so here it is:

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr = [];
  var len = arr.length;
  for (var i = 0; i < len / size; i++){
    newArr.push(arr.slice(0,size));
    arr.splice(0,size);
    console.log( 'Loop ' + i + ' :' +newArr );
    console.log( arr );
  }

  console.log( newArr );
  return newArr;
}

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

Thanks! I was really close to finish just like you, but I was slicing my array in wrong points. Your solution clarified some things up :slight_smile:

Hi everyone, just want to thank you for posting your solutions. I managed to solve it but I didn’t use “slice”, only “push”. Somehow I got stuck in a line of thought and tried to get a solution no matter what. But seeing your elegant and concise solutions made me realize I should have approached it in a different way. And that’s really useful. Here’s my code:

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var arrFinal = [];
  var arrToPush = [];
  var resetArr = 0;
  
  for( var i = 0; i < arr.length; i++){
      
      if (resetArr < size) {
        arrToPush.push(arr[i]);
        resetArr++;
        
        if (resetArr === size || i + 1 == arr.length){ // se exceder o size ou for a última posiçã
          arrFinal.push(arrToPush);
          arrToPush = [];
          resetArr = 0;
        }

      }

  }
  //console.log(arrFinal);
  return arrFinal;
}

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

here’s my solution if anyone is interested. :slight_smile:

This thread was helpful in coming to my answer, so maybe it will continue to help others as they look for help

function chunkArrayInGroups(arr, size) {
          //Make segment picker beginning
          var sliceStart = 0;
          //Make segment picker end
          var sliceEnd = size;
          //Make answer array
          var outarr = [];
          ///Loop through array in increments of the size param
          for (var i = 0; i < arr.length; i = i + size) {
            //push the slices to the answer array
            outarr.push(arr.slice(sliceStart,sliceEnd));
            //Increment the segment pickers
            sliceStart += size;
            sliceEnd += size;
          }
          //Answer out
          return outarr;
        }

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

Here’s my solution, pretty simple. Not that the challenge is that simple, my code is.

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

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

I chose to use splice as well, but forgot to follow up with a sub-array! This was a huge help! Thanks!

var newArray = [];
        
   while (arr.length){
    newArray.push(arr.splice(0, size));
   }
  return newArray;

@rmdawson71 I see your point. It definitely make sense.