The simplest way to shuffle an array in JavaScript is to provide a custom function to a .sort()
.
1 |
array.sort((a, b) => 0.5 - Math.random()); |
But the best way to shuffle an array and have a truly random distribution of items, you have to implement the Fisher-Yates algorithm.
1 2 3 4 5 6 7 8 |
const shuffleArray = array => { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = array[i]; array[i] = array[j]; array[j] = temp; } } |
Shuffle Array JavaScript Example
Complete HTML example codes:
Simple way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <body> <script> function shuffle(array) { array.sort(() => Math.random() - 0.5); } let arr = [1, 2, 3, 4, 5]; shuffle(arr); alert(arr); </script> </body> </html> |
Output:

The Fisher-Yates algorithm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<!DOCTYPE html> <html> <body> <script> function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } var arr = [1,2,3,4,5]; console.log(shuffleArray(arr)); </script> </body> </html> |
Output:

How to Shuffle an Array and Return a New One in JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <body> <script> function shuffleArray(array) { var copy = [].concat(array); copy.sort(function(){ return 0.5 - Math.random(); }); console.log(copy); } var original = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; shuffleArray(original); console.log(original); </script> </body> </html> |
Output:

Do comment if you have any doubts and suggestion on this JS Array topic.
Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version