I've been completing challenges on FreeCodeCamp and stumbled upon this solution for an algorithm. Can't comprehend how the if else statement works here.
function chunkArrayInGroups(arr, size) {
var temp = [];
var result = [];
for (var 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;
}
Why is temp = []
at the end of the else
block?
temp = []
means "reset the temp
variable to an empty array"
in the if block, the arr[a]
element is pushed at the end in the temp
array.
in the else block, the same happens AND the whole current temp
array is added at the end of the big result
array of arrays, and the temp
array is reset to the empty array.
Cannot say much more since there is not data or context written in your question. Hope this has answered your question.
The function divides an array into chunks of small arrays where the 'size' parameter defines the length of each chunks array. The algorithm works as follows:
else block - push element into temp array, push temp array into results array and create new empty temp array ();
at the end if temp array length is not 0 then push it also into results array. that's it :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With