A quiz shows its answers in a random order. A music player has a shuffle button. A card game deals from a shuffled deck. In each case "random" has to mean fair: every possible order equally likely. Many shuffles that look random are not. Some orders come up far more often than others, and some never come up at all, which a player of a card game or a reviewer of a quiz will eventually notice.
Write shuffle(array) in shuffle.js. It returns a new array with the same items in a random order, where each of the possible orders is equally likely.
The result is a new array with exactly the same items, the same number of times each (repeated values and objects included).
The input array is not changed. An empty array gives a new [], and a one-item array a new one-item array.
Every order is equally likely: for 3 items, each of the 6 orders comes up about one time in six.
Every item is equally likely to end up in every position, including the one it started in.
All the randomness comes from Math.random: the same sequence of random numbers gives the same order. Different sequences usually give different orders, but not always: many random numbers lead to the same choice (with two items, 0.1 and 0.2 can pick the same place), so two sequences can give the same order.
It works whatever Math.random returns in its range, including 0 and numbers just below 1.
Plain JavaScript in a browser page; the tests call the global shuffle from shuffle.js.
The tests replace Math.random with a seeded generator, so each run is repeatable. They shuffle tens of thousands of times and check that the counts of each order are as even as chance allows.
array.sort(() => Math.random() - 0.5) is not fair, and the tests will show it.
Think of drawing cards from a hat: pick one of all the cards for the last place, then one of the cards left for the place before it. How many choices does each place have?
If every place picks from all n positions, there are n to the power n equally likely runs. Can that number be split evenly among n! orders?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.