The Cash Register Project Array Mutation Problem

Tell us what’s happening:

Hey fellas! i am in the last challenge to end the data structures and algorithms section , but i got a weird problem
my solution for the cash register project consists of making a clone for the Cid array called “original” , and i enter a for loop that will iterate through the cid array and mutate it if it necessarily.
then when i quit the loop i will compare between the “cid” and the original cid array called “original”
the problem is that “original” is mutated too and it became a clone of cid so i cant compare and get the change.

i dont understand why i got this problem
and thanks for help!

Your code so far

var currency = {
  "Penny" : 0.01,
  "NICKEL" : 0.05,
  "DIME" : 0.1,
  "FIVE": 5,
  "TEN": 10,
  "TWENTY": 20,
function checkCashRegister(price, cash, cid) {

var change =0;
var rest = cash - price;

   var original = cid.slice(0);
   console.log("cid clone before the loops");

for(var i= cid.length-1;i>=0 && change<rest;i--){
  while(cid[i][1]!=0 && change<rest && change+currency[cid[i][0]]<= rest ){
            cid[i][1]= cid[i][1]-  currency[cid[i][0]];  

console.log("cid clone after the loops ");

    change = original.filter((v,i)=>v[1]!=original[i][1]);


checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

Your browser information:

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

Challenge: Cash Register

Link to the challenge:

Idk what exactly are the exercise requirements but if you google: copy array in python (not cloning) you’ll found out.

For example:

my_list = ['cat', 0, 6.7]
new_list = my_list.copy()

in this case new_list and my_list are independent.

you are correctly making a copy of the outer array, but you have copied a reference to all of the inner arrays

to copy you need to cooy both the outer and the inner array
something like
copy = => subarr.slice())

1 Like

I dont understand what do you mean ?

this doesn’t make a copy because your array is multidimemsional

you need to make a copy also of the inner arrays, above I showed a way

1 Like