Splice() modifica todos los arrays sin control

Quiero insertar un array en otro array en un índice n pero conservando el array original

No se porqué, la funcion splice() modifica todos los arrays que encuentra, por ej. arr2 o arraySeguro, que son arrays copias de arr2, no deberían ser modificados, pero sin embargo, después del bucle for, se modifican.

Incluso declaro constante a el arraySeguro, para que no sea modificado, pero se modifica igual, no entiendo. :roll_eyes:

El ejercicio que estoy intentando resolver es el siguiente:

Tienes dos arreglos y un índice.
Copia cada elemento del primer arreglo en el segundo arreglo, en orden.
Comienza insertando elementos en el índice n del segundo arreglo.
Devuelve el arreglo resultante. Los arreglos de entrada deben permanecer iguales luego de que se ejecute la función.

`
function frankenSplice(arr1, arr2, n) {
let nuevoArray = arr2;
const arraySeguro = arr2
for (let i = arr1.length-1 ; i >= 0; i–){
nuevoArray.splice(n, 0, arr1[i])
//console.log(i)
}
console.log(nuevoArray)
console.log(arraySeguro);
return arr2;
}

frankenSplice([“claw”, “tentacle”], [“head”, “shoulders”, “knees”, “toes”], 2);//

`

Información de tu navegador:

El agente de usuario es: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36

Enlaza al desafío:

Hi @dariofinelli, mi Español es básico, por eso me resulta tan difícil explicar este concepto en español, espero non te molestas voy a usar ingles.

In JS there are two ways in which memory is passed.
By value and by reference.

All primitives are passed by value. So imagine that for each new variable you get a new value as well:

var x = 2
var y = x

y = y + 1 // 3
x // 2

Object (so Array as well) on the other hand are passed by reference. This means that instead of sharing a “chunk” of memory, you are sharing the “address” in memory where those values are stored.

This means that when you assign a variable to an array/object you are in fact sharing where that value lives.
Which means:

var x = [0,1,2]
var y = x // you are sharing the same address

y[0] = "foo"
y // [ 'foo', 1, 2 ]
x // [ 'foo', 1, 2 ]

Modifying y changed x as well, because both are looking at the same address in memory.

If you want to make a copy of an array, you need to find a method that returns a new array, meaning a totally new space in the memory.
For example slice returns a new array.
So I can use:

var x = [0,1,2]
var y = x.slice() // returns a new array

y[0] = "foo"
y // [ 'foo', 1, 2 ]
x // [ 0, 1, 2 ]

And is working as you imagine.

Espero este te puede ayudar, se tiene mas preguntas o dudas soy seguro que alguno con un nivel mas alto de espanol puede ayutarte mas :smiley:

Happy coding :sparkles:

Hi Marmiz, thanks for your reply and dont’ worry, my english level is bad but we will understand.

I understand your explanation.
So, when I assign as value of the y variable the x variable, both keep relationed or vinculated as in the same place of memory.

This is a surprise for me, after months of studying JS this is the first time that I will be apply this concept.

I’am graphic designer, and in Adobe Illustrator, something similar happens. By default, when you import a image file inside the .ai document, this image keep vinculated. So, if you change this image file, out of Illustrator, as with Photoshop, this image change too in the ai. document.

Thanks again, I try again with my JS code.

Best regards. :slightly_smiling_face:
Darío.-

Hola @dariofinelli,

Hice un video que creo que te puede ayudar a entender mejor lo que esta pasando. Como puedes ver en el video “las flechas apuntan al mismo arreglo”.

Cheers and happy coding :slight_smile: