Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading