Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chunk Array into groups - what's wrong with my code?

Below is the code :

function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr =[];
  for(var i = 0;i < arr.length;i++){
    for(var j = 0;j < size;j++){
      newArr.push(arr.splice(0,size));
    }
  }
  var result = [];
  for(i = 0;i < newArr.length;i++){
    if(newArr[i].length != 0){
      result.push(newArr[i]);
    }
  }
  return result;
}

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

This should return - [[0, 1], [2, 3], [4, 5], [6, 7], [8]]. However, the code returns [[0, 1], [2, 3], [4, 5], [6, 7]]. Also, if my input array is ([0,1,2,3,4,5,6,7,8,9,10],2) my code returns as expected.

P.S: I am specifically looking to find what's wrong with this code instead of a different code/approach altogether.

like image 448
sulabh chaturvedi Avatar asked Aug 12 '26 11:08

sulabh chaturvedi


1 Answers

Basically you need just one loop, because you splice the array and take a chunk of the wanted size of it.

This behaviour could be used to loop until the array has a length of zero and exit the loop.

In this case the result is ready.

function chunkArrayInGroups(arr, size) {
    var newArr = [];
    // for (var i = 0; i < arr.length; i++) {
    while (arr.length) {                        // add this for looping and checking
        // for (var j = 0; j < size; j++) {
        newArr.push(arr.splice(0, size));       // keep this for doing the work!
        // }
    }
    // var result = [];
    // for (i = 0; i < newArr.length; i++) {
    //     if (newArr[i].length != 0) {
    //         result.push(newArr[i]);
    //     }
    // }
    // return result;
    return newArr;                              // return only newArray
}

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 173
Nina Scholz Avatar answered Aug 15 '26 01:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!