This code works as far as getting even number of sub arrays, like [2,3],[5,7] in [2,3,5,7],2
but it doesnt do the remaining elements if there are some left over as in [2,3,5,7,6],3 so the left over ones would be [7,6]. This should be taken care of by the code that follows the ending bracket of the first for loop, but somehow it doesnt work. Am I missing something on the scope level for the arrCtr value? Doesnt let when used outside any loops create a global variable?
Your code so far
function chunkArrayInGroups(arr, size) {
let len=arr.length;
let divArr=[];
let newArr=[];
let numDiv=len/size;
var arrCtr=0;
let remainElements=len%size;
for (let divNum=0; divNum<numDiv; divNum++)
{
divArr=[];
for (let element=0; element< size; element++)
{
divArr.push(arr[arrCtr++]);
}
newArr.push(divArr);
}
divArr=[];
if (remainElements>0)
{
for (let i=0; i<remainElements; i++)
{
divArr.push(arr[arrCtr++]);
}
newArr.push(divArr);
}
return newArr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey