JavaScript Shuffle Function Not Shuffling Properly

23 Views Asked by At

I'm trying to write a function in JavaScript that shuffles the elements of an array. I came up with the following code:

function shuffle(array) {
  // Loop through the array
  for (let i = 0; i < array.length; i++) {
    // Pick a random index from 0 to array length (incorrect)
    const j = Math.floor(Math.random() * array.length);
    
    // Swap the current element with the randomly picked element
    [array[i], array[j]] = [array[j], array[i]];
  }
  
  // Not returning anything (modifies original array - not ideal)
}

When I run the code, the elements don't seem to be shuffled randomly. Additionally, the original array seems to be modified directly.

Can anyone help me identify the issues with this code and suggest improvements?

I'd appreciate it if the solution addresses:

Ensuring a proper random shuffle Returning a new shuffled array (without modifying the original)

1

There are 1 best solutions below

0
Padam Ghimire On
function shuffle(array) {
  const newArray = array.slice(); // Create a shallow copy of the original array
  
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1)); // Pick a random index from 0 to i
    
    // Swap elements between i and j
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  
  return newArray; // Return the shuffled array
}