My code is always very long

Continuing the discussion from freeCodeCamp Challenge Guide: Chunky Monkey:

So I solved the challenge with a solution I don’t see here. The problem is many of my solutions have been longer than the solutions shown. for this challenge, I used 3 for loops.

How do I get better at shortening my code? I feel like there are so many methods to remember and ways of doing things I’m just not thinking of and I end up overcomplicating the solution.

Here is my solution.

function chunkArrayInGroups(arr, size) {
  let newArr = [];
  const count = arr.length/size;
  for (let i = 0; i < count; i++) {
    let tempArr =[];
    if (arr.length >= size) {
      for (let j = 0; j < size; j++) {
      tempArr.push(arr[j]);
      }
    } 
    else if (arr.length < size) {
      for (let k = 0; k < arr.length; k++){
        tempArr.push(arr[k]);
      }
    }
    newArr.push(tempArr);
    arr = arr.slice(size);
  }
  return newArr;
}

This is hard, so don’t worry. It comes with practice.

You are sorta looking at this the wrong way around. You want simpler code. Simpler code is often shorter. Shorter code isn’t always simpler.

Those two inner loops look very similar. Can you make them into one loop? That would be simpler.

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