Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!