To shuffle(randomize) an array in JavaScript, you can use the “Fisher-Yates (aka Knuth) Shuffle algorithm”.
Example
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const myArray = [11, 19, 18, 46, 21];
const shuffledArray = shuffleArray(myArray);
console.log(shuffledArray);
Output
// Run
[ 21, 19, 46, 18, 11 ]
// Run again
[ 46, 18, 11, 21, 19 ]
// Run again
[ 46, 19, 18, 21, 11 ]
// Run again
[ 21, 11, 46, 19, 18 ]
In this implementation, the shuffleArray() function takes an array as an argument and shuffles it using the Fisher-Yates Shuffle algorithm.
Here’s how it works:
- The shuffleArray() function starts by iterating over the array from the end to the beginning, using a for loop with a decrementing index (i).
- For each loop iteration, a random index (j) is generated using the Math.random() method and the current value of i.
- The current element at index i is then swapped with the element at index j, using array destructuring syntax.
- After all iterations of the loop have been completed, the shuffled array is returned.
You can see that running the above file will give us the shuffled version of the original array. Note that the shuffleArray() function does not modify the original array, as a new shuffled array is returned instead.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.