0

So I need the original(argument) array to stay the same, AND have another array (array2) with it's values to make some changes on it but mantain the original(argument) array intact.

Example:

let wtf = function(array){
    let array2 = array
    array2[0] = array2[0].replace(array2[0][0],"1") 
    console.log( array + " "  + array2)
}

wtf(["a","b"])

Result in console: 1,b 1,b

BUT I need a,b 1,b (that comes from: array = a,b and array2 = 1,b )

Thanks!

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Mariano
  • 3
  • 2
  • 1
    Does this answer your question? [Copy array by value](https://stackoverflow.com/questions/7486085/copy-array-by-value) – sinanspd Dec 28 '19 at 02:02

1 Answers1

0

I think this is a reference value vs a clone value problem.

With your let array2 = array line, I think you're creating a reference to the same in-memory object, so you're actually modifying a single array twice, even though it looks like you've created another one.

To create a 'true' clone you can try something like:

let array2 = JSON.parse(JSON.stringify(array));
courtness
  • 76
  • 7