How to implement the Fischer-Yates shuffle in JavaScript

What follows is an in-place reference implementation of the Fischer-Yates shuffle which is categorized as an unbiased, efficient shuffle.

This shuffle will randomly assort the contents of an array by mutating the array directly.

The algorithm’s time complexity is O(n).

shuffleTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function shuffle(array) {
let len = array.length, randomIndex, temp;
while (len) {
// Select a random index between 0 and len, exclusive
randomIndex = Math.floor(Math.random() * len--);
// Swap element at len and randomIndex
temp = array[len];
array[len] = array[randomIndex];
array[randomIndex] = temp;
}
return array;
}
const array = [1, 2, 3, 4, 5, 6, 7]
shuffle(array);