The Knuth shuffle, randomize arrays, JavaScript

Based on the Fisher-Yates shuffle, the Knuth shuffle requires less overhead. FYS stimulates that you should remove a random item out of the original array and place it in a new array, and repeat while never fetching from the same location twice.

The Knuth shuffle simply swaps the random item with the last item in the array.

1
2
3
4
5
6
7
8
9
function shuffle(arr) {
let i = arr.length, j;
while (i) {
j = Math.floor(Math.random() * i--);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9]); // [4, 9, 7, 1, 2, 6, 8, 5, 3] ...