Workshop › Memory › Step 12 of 25
Right now the pairs sit side by side. We shuffle the deck with the Fisher–Yates shuffle: walk from the last position to the first, and swap each one with a random position from 0 up to it. Every order is equally likely.
```js
// Fisher–Yates: every order is equally likely.
function shuffle(items) {
for (let i = items.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[items[i], items[j]] = [items[j], items[i]]
}
return items
}
const deck = shuffle([...SYMBOLS, ...SYMBOLS])
```i goes from the last position down to 1 (i-- subtracts 1).j is a random position from 0 to i: Math.random() is 0 up to 1, times i + 1, rounded down.[items[i], items[j]] = [items[j], items[i]] swaps the two items. The leading ; stops JavaScript from gluing the
line onto the one before.i; picking j from the whole array would be biased too.function newGame, write the comment and shuffle, then an empty line.newGame, wrap the deck in shuffle( ... ).Skills: Arrays and objects, Functions
← The face of a card Which card is at a point? →