Misunderstanding arrays

Hello, when I did the last project in “JavaScript Algorithms and Data Structures Projects” I saw a thing that I could not explain: I tried to copy the array in all the ways I knew, but to no avail, they all mutated. I solved this problem in a different way, and solved the problem (160 lines lol) but I’m still confused. this is probably a very stupid question, so I will be glad if you just leave a link so I can figure it out. thanks in advance!

function checkCashRegister(price, cash, cid) {
  let startedValue = cid.slice()
  let test = [...cid]
  let veryTestedArray = []
  for (let i = 0; i < cid.length; i++){
    veryTestedArray.push(cid[i])
  }

startedValue[0][1] = startedValue[0][1] - 0.5
console.log(startedValue)
console.log(cid);
console.log(test)
console.log(veryTestedArray);

return cid

}


checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);

this happen because cid is a multidimensional array, you also need to copy the inner arrays.
You could do
let test = cid.map(ar -> [...ar])
(or same thing for your push method, where you would need to push [...cid[i]])

or one thing that works for any depth of arrays (and objects) is:
let test = JSON.parse(JSON.stringify(cid))

you could use this for a visual rappresentation of the result of your ways of copying:
http://www.pythontutor.com/javascript.html

1 Like