As I understood that when using the Spread operator (...) it copied the elements of the array and if it was put in another variable (newArray) it created a different array linked to the first array (array) that is to say that from then on it could modify newArray and it would not affect array but if it modified array if it modified newArray... but I see that this is not the case, can someone explain to me why and what would be the best way to copy the elements of a parameter into a new variable that does not affect the parameter data original??
function modificar (array){
let nuevoArray =[...array]
console.log(array)
console.log(nuevoArray)
nuevoArray[0][1]='esto afecta a los dos arrays'
console.log(array)
console.log(nuevoArray)
}
modificar([['a','b'],['c','d']])
We must change the internal reference in newArray[0] to a new array which we will create by applying the propagation operator again
nuevoArray[0]=[...array[0]]
The spread syntax reaches a level of depth when you copy a multidimensional array. Therefore, it does not allow you to modify your multidimensional array
nuevoArray
in such a way that itnuevoArray
does not modify the original at the level that you intend to do so, in order to do so, you have to apply the spread operator again Because you are internally accessing the new Array at a depth level in which the first spread does not reach, because when you modify b, that modification will be reflected in the originalnuevoArray.push('Hola array desde nuevo:');
original : [ [ 'a', 'b' ], [ 'c', 'd' ] ]
nuevoArray[0][1].push('Hola array desde nuevo :');
//original luego de push() profundo:[ [ 'a', 'b', 'Hola array desde nuevo :' ], [ 'c', 'd' ] ]
nuevoArray[0]=[...array[0]]
and other drawbacks of JSON.parse(JSON.stringify(obj))
With spread: