function chunkArrayInGroups(arr, size) {
let temp = [];
const result = [];
for (let a = 0; a < arr.length; a++) {
if (a % size !== size - 1) temp.push(arr[a]);
else {
temp.push(arr[a]);
result.push(temp);
temp = [];
}
}
if (temp.length !== 0) result.push(temp);
return result;
}
chunkArrayInGroups(['a', 'b', 'c', 'd'], 2);
Please Tell us what’s happening in your own words.
Learning to describe problems is hard, but it is an important part of learning how to code.
Also, the more you say, the more we can help!
The task is to chop up the array by size. In order to achieve this there are two variables, temporary and result. A for loop is doing the chopping. We need the length of the array and its data. There is an if statement with a condition and an else branch. If the condition is fulfilled then it pushes one value (arr[a]) into temp and then the for loop goes to the next value. If the condition is not fulfilled then it jumps to the else branch and executes it. My problem is that I do not understand the condition.
It says that, if a (remainder) % size not strictly equal to size-1 then… But what is the logic behind it.
If I am calculating right then first a=0, so the remainder is 0. This is not equal to size-1 so condition fulfilled and it it pushes arr[a] into temp.
most of the time is the if that execute, the else
happens only sometimes.
You may want to create a small table where you calculate a % size
and note if a % size !== size - 1
is true or false. Do this again and again for different values of arr
and size
.
I just did it. I realized that is always one and zero. I got the logic. Thanks!!!
it’s not always one and zero, use a bigger size
to see