Basic Algorithm Scripting - Chunky Monkey

if (temp.length !== 0) {//result.push(temp);
this line in the code is useful,i mean we already declared temp variable to be empty, so we know that temp variable is empty so why checking the temp variable to be even though we know that temp is empty; how does that code help to get answer!

Your code so far

function chunkArrayInGroups(arr, size) {
  let temp = [];
    let 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);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Chunky Monkey

Link to the challenge:

i’m not sure I understand you well.
temp was an empty array before the for loop ran…
but after the for loop is done, it may or may not be empty?
the if is saying that if it is not empty then add it to the result?

Not sure if this answers you at all …

Hi,
First be careful with your code, the “return result” is on the wrong site and this code doesn’t work.

Once corrected, try to comment only this:

if (temp.length !== 0) 

And check the result for this, with the above code commented and uncommented

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4));

So here you will see the purpose of that if.

The key here is that it depends on each case, there are pending results due to the push of the temp variable, and we need to check if it has to add them or not, in the case of being empty, we don’t want it to add an extra empty array, but otherwise we want which adds the remaining array.

I recommend you use console.logs, so you can see the variable values.