Chunk the given array into the given size

This is the solution I came up with: every other test case seems to be passing except for this one:: chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2). please help!!

Your code so far

function chunkArrayInGroups(arr, size) {
    // Break it up.
    let newArr = [];
    for ( let i = 0; i < arr.length; i++ ) {
        if ( arr.length > size ) {
            newArr.push( arr.splice(0, size) ); 
        }
    }
    newArr.push(arr);
    return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);

Challenge: Chunky Monkey

Link to the challenge:

To expand a bit on what Randell said, this is a good example of why you want to avoid mutating an array that you are currently iterating over. Because the values at an index change with every iteration, you can’t just march through an iterator the way that you expect to.

Please, what can I do next?

My suggestion is not to use arr.splice in a for loop.

2 Likes

OK.
I changed from using the for-loop to using a while-loop and it worked. Thank you all for your support. below is my new code:

function chunkArrayInGroups(arr, size) {
    let newArr = [];
    while (arr.length > size) {
      newArr.push(arr.splice(0, size));
    }
    newArr.push(arr);
    return newArr;
  }

Congratulations on figuring it out! Happy coding.

I added the i-- after initializing i = arr.length; it still produced the same result only that it increases the number of code lines…

Now, consider:

const arr = [1];
const chunk = arr.splice(0, 1000);
console.log(chunk); // [1] ;)

… and taking this snippet into account try to refactor your function. You do some unnecessary things there :slight_smile:

1 Like