Basic Algorithm Scripting - Chunky Monkey - Solution

Tell us what’s happening:

So, here is my inelegant solution. Could I get some constructive feedback?
The solution forum is unlocked but I can’t seem to respond.

Your code so far

function chunkArrayInGroups(arr, size) {
  let newArr = [];
  let nestArr = [];

  if (size < 1) { return arr}; // Ensure size cannot be less than 1, preventing infinite loop.

  for (let i=0; i <= arr.length; i++) {
    while (nestArr.length < size) {
      let shiftValue = arr.shift(); // Value = arr[0]

      if (shiftValue === undefined) { // If no elements remain
        break; // Stop the loop
        } else {
          nestArr.push(shiftValue); // Otherwise push the value to the nestArr so long as the nestArr is less than the 'size' attribute.
        }
    }
    newArr.push(nestArr); // Finally, push the nestArr to newArr.
    nestArr = []; // Reset nestArr for next iteration.
    i=0; // Reset i, as the original arr.length has changed.
  }
  console.log(newArr)
  return newArr;  
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);

Your browser information:

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

Challenge Information:

Basic Algorithm Scripting - Chunky Monkey

1 Like

Can you think of a way to avoid this?

1 Like

Nope. ha. So I realised that mutating the original array was unwise and causing unnecessary complications.

Instead, I opted to use slice and use the ‘size’ parameter to increment i.

function chunkArrayInGroups(arr, size) {
  if (size < 1) { // Prevent infinite loop
    return arr;
  }

  let newArr = [];

  for (let i = 0; i < arr.length; i += size) {
    let chunk = arr.slice(i, i + size);
    newArr.push(chunk);
  }

  return newArr;
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);

That’s much easier to read!

One tweak - I’d declare those arrays as ‘const’

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.