Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
How can i make 2 different shuffled arrays from an initial array? javascript

How can i make 2 different shuffled arrays from an initial array in javascript?

When i execute my code the 2 shuffled arrays are always the same. I want my initial array to be unchangeable and the 2 new arrays to be differently shuffled.

Thank you!

const array = [
{
 name: "Nick",
 age: 15,
 grade: 18
},
{
 name: "John",
 age: 16,
 grade: 15
},
{
 name: "Patrick",
 age: 13,
 grade: 11
},
{
 name: "George",
 age: 15,
 grade: 19
}
];

console.log(array);

function shuffle(array) {
 let currentIndex = array.length,  randomIndex;

 while (currentIndex != 0) {

  randomIndex = Math.floor(Math.random() * currentIndex);
  currentIndex--;

  [array[currentIndex], array[randomIndex]] = [
    array[randomIndex], array[currentIndex]];
 }

  return array;
 }

 let array1 = shuffle(array);
 console.log(array1);

 let array2 = shuffle(array);
 console.log(array2);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

All you have to do is add the .slice:

 let array1 = shuffle(array.slice());
 console.log(array1);

 let array2 = shuffle(array.slice());
 console.log(array2);

The .slice means that you create a "copy" of the original array rather than modifying the existing array.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda