0

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);
akis
  • 1
  • 2
  • [javascript - Copy array by value - Stack Overflow](https://stackoverflow.com/questions/7486085/copy-array-by-value) (shallow only) – user202729 Dec 06 '21 at 10:12
  • Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Justinas Dec 06 '21 at 10:12
  • Both [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) and [the rest syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters#rest_parameters_are_real_arrays_the_arguments_object_is_not) on a [destructured array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#assigning_the_rest_of_an_array_to_a_variable) each generate a shallow array copy ... `let array1 = shuffle(Array.from(array)); let array2 = shuffle([...array]);` – Peter Seliger Dec 06 '21 at 10:24

1 Answers1

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.

Dylan Kerler
  • 2,007
  • 1
  • 8
  • 23