Mutation Problem

I’m wondering why this code changes BOTH newCID and cid? Can anyone help to explain? Thanks!

Edit: This is the JavaScript Algorithms and Data Structures Projects: Cash Register. I don’t

  var cid = [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]];
  var newCID = cid.concat();
  var registerValues = origCID.reverse().map(function(item) {
    item[1] = item[1] / monetaryValues[count];
    count += 1;
    return Math.round(item[1]);

When I run my program, both arrays turn into:

//cid (the original is now)
PENNY,101,NICKEL,40.99999999999999,DIME,31,QUARTER,17,ONE,90,FIVE,11,TEN,2,TWENTY,3,ONE HUNDRED,1
//newCID is now 

However, I’d like to keep one original version and just modify the copy.

Edit: Including more information

Please provide whole code and the challenge link
It is impossible to know what’s going on, this seems just a part of your code, and it is not entro know what’s going on

reverse modifies the array in-place, it’s a mutating method.

Edit: just noticed you make a copy of it. If it’s not reverse, then can you give an example of what the values are in cid? Are they objects by any chance? Because you’re only making a shallow copy, which is fine if the array is just primitive values (eg all numbers of strings or whatever). But if it isn’t, a shallow copy isn’t going to make new copies of whatever the values are — you will be modifying the exactly same objects.

1 Like

Thanks Dan, here’s the array it’s modifying or at least an example of it.

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

So the values inside the array are themselves arrays. When you clone it using concat, it does make a copy of the array. But the sub-arrays are objects, so for each value, what gets copied is a reference to each of those sub-arrays. That reference still points at the same array it did originally.

With this, what you could do is replace the cid.concat() with something like (item) { return item.concat(); }). It’ll do the job: you’ll get a copy, and each of the items in the array will be actual copies, too.

Thank you! That’s definitely where I was getting confused. Appreciate the help!

1 Like