Help with javascript Array mutation

Hello! I’m doing the changeMachine project in JS. I want to take “cid” array from the arguments and work with it, but without changing it (I need it later). Then I create two new arrays (originalCid and cidMutable) using cid.slice() method. I thought that after using this method, I would be able to modify the new arrys with no mutation of the original one, but that’s not happening. Can anybody say me why?

As it can be seen, at line 5 I’m modifying cidMutable, and in the console we can see that cid has been also modified.

Thanks!!

don’t use cid.slice() with no params… use spread operator originalCid = […cid] for example.

please, don’t post screenshots, copy and paste your code (with proper formatting) or use a repl.it or jsfiddle or codepen or whatever you want

I think the thing is that you have made a copy of the array cid but each array inside the copy is still a reference to those arrays inside cid

I copied a multidimensional array with slice like you did, and this is what happen (the same happen with the spread operator, so @oristar2018 suggestion will still have the same effect) :

You can try changing approach, or trying to figure it out yourself how to make this work
or this would work if you want the help:

let copy = cid.map(e => [...e]);

I tried it and it didn’t work either!

Thanks

Thanks! I will post my code next time, I didn’t thought it’s easyer to replicate the problem if all the code is posted!

This comment:
I think the thing is that you have made a copy of the array cid but each array inside the copy is still a reference to those arrays inside cid

Oh my God, it’s really weird… I woult have never thought that the problem was that one… I have found this topic talking about it:

Thanks @ilenia, thank you so much!