Implement the Chunky Monkey Algorithm - Implement the Chunky Monkey Algorithm

Tell us what’s happening:

I finally completed the tests, does anyone have any comments or recommendations on my code?

Your code so far

function chunkArrayInGroups(array, n) {
  const arraysWithSamelength = Math.floor(array.length / n);
  let splitCount = arraysWithSamelength;
  if (array.length % n != false) splitCount++ ;
  const newArray = [];
  for (let i = 1; i <= splitCount; i++) {
    if (array.length > n) {
      newArray.push(array.splice(0, n))
    } else {
      newArray.push(array)
    }
  }
  return newArray
}


console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4))

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36

Challenge Information:

Implement the Chunky Monkey Algorithm - Implement the Chunky Monkey Algorithm

1 Like

Few notes:

  • arraysWithSamelength is defined just to reassign it in the next line to splitCount.
  • The array.length % n != false condition works because != operator tries to convert both sides to the same type. array.length % n could be instead strictly compared to the actual integer, to more explicitly show condition. Otherwise, since condition in if will be considered in a boolean context, it means that array.length % n alone would be considered to be either truthy or falsy, comparing it to with != false is like saying: check if it’s not falsy. This is what if (condition) does on it own.
  • splitCount appears like a helpful number. After all it’s good to know how many times to loop in the for loop. Is it really needed though? There’s a bit troubles to calculate it , one value is floored with Math.floor, then sometimes result is incremented, sometimes not. What happens inside of the loop can give some idea how it could be handled without the need for splitCount.
1 Like

Good work on passing all the tests! There are few steps in which way you can clean the code and make it more efficient.

  1. You’re using splice(), which modifies the original array. This isn’t the best way, as it’s better to use slice() instead, as it doesn’t modifies the original array.

  2. There’s no need to compute the number of chunks before, as it makes the code more complex. You can simplify the logic by looping through the array and incrementing by n.

  3. The condition array.length % n != false is confusing because it mixes types, it’s more clearer and simpler to check directly if the remainder is not zero.

Let us know if this helps, good luck!

2 Likes