function chunkArrayInGroups(arr, size) {
// Break it up.
var local = [];
var currPos = 0;
var length = arr.length;
for(var x = 0; x< length%size;x++){local[x] = [];}
if(length - currPos > size){
for(var i = 0; i< size; i++,currPos++){
local[(i+1)%size - 1].push(arr[i]);
}
}
for(var j = currPos; j< length; j++){local[j%size].push(arr[j]);}
return local;
}
chunkArrayInGroups([“a”, “b”, “c”, “d”], 2);indent preformatted text by 4 spaces
first loop
;x < length % size;
if x === 0
at beginning and this second expression when u check if this equal to ur desired, is equal to 0 then loop will never work
u got in frist for loop now something like
length % size === 4 % 2 === 0
for ( 0; 0 < 0; 0++)
So u may want to write this like
for ( var x = 0; x < length / size; x++ )
And u can do the job without this first loop see below next part
Second loop
i don’t understand why u wrote like
local[(i+1)%size - 1].push(arr[i]);
it goes something like with this:
evaluated:
i: 0
local[0].push(arr[0]);
i: 1
local[-1].push(arr[1]);
U may want to write like this
two loops
first loop to go from 0 to number of chunks - outer
second loop to go from 0 to size of chunk - inner
something like:
var indexArr = 0;
for ( var i = 0; i < length/size; i++ ){ // outer loop
var node = []; // chunk for array
for ( var y = 0; y < size; y++ ) // inner loop
node.push(arr[indexArr++]); // pushing into node chunk
local.push(node.splice(0); // pushing chunk into array that u need to return
}