What principle am I ignorant to causing array to mutate in loop

Tell us what’s happening:
The code is to Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.

When debugging, the arrays are generated as they should initially, then plushed to the output array (empty array), but every step towards the complete output array with the “next” pushed array, the entire set of arrays in the output array becomes the next array.

example based on below code. First loop builds out newArr[0,1,2]
on second round through loop, newArr[[3,4,5],[3,4,5]]

  **Your code so far**
function chunkArrayInGroups(arr, size) {
  let arrNum = arr.length / size
  console.log(arrNum)
  let newArr = []
  let arrNext = []
  for (let i = 0; i < arrNum; i++) {
    for (let j = 0; j < size; j++) {
      arrNext[j] = arr[j]
    }
    newArr[i] = arrNext
    arr = arr.splice(size, arr.length - 1)
  }
  console.log(newArr)
}



      **Your browser information:**

User Agent is: <code>Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36</code>.

**Challenge:** Chunky Monkey

**Link to the challenge:**
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey

What this code does?
What it should/shouldn’t do?
What have you tried?

Your question and code are not clear.

fixed, thanks. Submitted incomplete question prematurely.

you have two versions of the code there, which one of the two are yoo asking about?

The first set of code

you are storing a reference to the same array, not a copy - if you want to copy it, try to resesrch a method to use

if you look at your code with Online JavaScript Compiler, Visual Debugger, and AI Tutor - Learn JavaScript programming by visualizing code you can see that it is the same array

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