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)