JavaScript doubt: clutter array with loop

0

I am doing an exercise for a job and I have a problem when messing an array. That is, I have an array called "numbers" and a function that messes up. Then I create an empty array called "disordered numbers" which I will fill with three positions, which will be three times the array "numbers" messed up differently. Why when I create the positions of the array "disordered numbers" with the function of cluttering the "numbers" array, does it always create the same clutter? I show you code and the result:

function desordenar(array){
  array = array.sort(function() {return Math.random() - 0.5});
  return array;
} // esta función me desordena un array

var numeros= ["1", "2", "3", "4", "5"]; //este es mi array

numerosDesordenados= []; // array vacio

for (i=0;i<3;i++){ //creo bucle para llenar array vacío
  numerosDesordenados[i] = desordenar(numeros);
}

If I do a console.log(numeros) it shows me in console ["1, "2", "3", "4", "5"] . Well ... If I do a console.log(numerosDesordenados) it shows me an array with three positions always with the same mixture, for example:

[0] = ["2","3","1","5","4"]

[1] = ["2","3","1","5","4"]

[3] = ["2","3","1","5","4"]

I want the three positions to be different. How can I do it?? Thank you very much!

    
asked by Miyūki Chiryoku 12.05.2018 в 18:15
source

1 answer

1

This happens because arrays in javascript are objects and variables are references to those objects, so when assigning from variable to variable it is the same object that is referenced / changed.

One way to make a "copy" of an array in a new object is with the propagation operator (spread syntax) that "expands" the array and so the elements in brackets create a new array: [... array ]

function desordenar(unArray){
  var t = unArray.sort(function(a,b) {return (Math.random()-0.5)});
  return [...t];
} // esta función me desordena un array

var numeros= ["1", "2", "3", "4", "5"]; //este es mi array

numerosDesordenados= []; // array vacio

for (i=0;i<3;i++){ //creo bucle para llenar array vacío
  x = desordenar(numeros);
  numerosDesordenados[i] = x;
  console.log(i,x);
}

console.log(numerosDesordenados);

note: I use the x within the loop just to make a log next to i

link

In the expression return [...t]; the "ellipsis" is the operador de propagación that what it does is take the elements of t and propagate them, or scatter them separated with commas, as this occurs inside the square brackets, the result is a new array.

    
answered by 12.05.2018 / 20:59
source