Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this if-else statement inside a function work?

Tags:

javascript

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?

like image 578
Peter Peach Avatar asked Dec 07 '22 13:12

Peter Peach


2 Answers

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 temparray.

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 temparray 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.

like image 105
Pac0 Avatar answered Dec 11 '22 09:12

Pac0


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:

  • iterate each array element (for loop) until main_array elements index is less than chunk array size (a % size !== size - 1), and push elements into temporary array.
  • 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 :)

like image 30
shakogele Avatar answered Dec 11 '22 09:12

shakogele