Can anyone help fix this newbie's code?

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**
function chunkArrayInGroups(arr, size) {
let newArr=[];
for (let i=0; i<arr.length/size; i++){
  let splicedArr;
  if(size<=arr.length){
  splicedArr=arr.splice(0, size);
  } else {
    splicedArr=arr;
  }
  newArr.push(splicedArr);
  console.log(splicedArr);
  console.log(arr);
  console.log(newArr);
  
}
return newArr;
}

chunkArrayInGroups(["a", "b", "c", "d","e"], 2);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Chunky Monkey

Link to the challenge:

I think you are making a bad assumption here. Look at the last few test cases. How many elements are in the array being passed in? What happens when you divide the length of those arrays by the size?

I thought that means how many times I need to loop the whole array.

What I was trying to get you to see is that the size does not always divide evenly into the arr.length. Look at the last test case. The length of arr is 9, so 9/2 = 4.5. Do you see why your for loop isn’t always going through the entire array?

weird. When I change splice to slice and the corresponding start & end, the same code works.

You’ll have to post your new code so I can see what you are doing.

function chunkArrayInGroups(arr, size) {
let newArr=;
for (let i=0; i<arr.length/size; i++){

let slicedArr=arr.slice(i * size, i * size+size);

newArr.push(slicedArr);
console.log(slicedArr);
console.log(newArr);

}
return newArr;
}

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

Ahh, ya, I was focusing on the wrong thing in your original code. The splice method changes the array that you call it on. So arr.splice(0, size) removes elements from arr. So each time the for loop does i < arr.length / size the length of arr is smaller because splice removed elements from it. So your for loop is going to exit earlier than you think because i keeps growing and arr.length keeps shrinking.

Thanks, mate. That’s correct. The remaining arr keeps shrinking, but what I spliced ervey time is the remaining arr’s[0,2], so it doesn’t splice 2 elements from the remaining arr?

Add a console.log('i=', i); at the beginning of your for loop and I think you’ll see what I am talking about. Also, add a console.log('newArr=', newArr); right before the return statement. It should become clear that your for loop isn’t doing enough iterations to produce the correct results.

How to fix it so that it does?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.