Workshop › Klondike Solitaire › Step 6 of 40
A new deck is in order. We shuffle it the fair way: going from the last card to the first, swap each card with a random card at or before it.
```js
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[deck[i], deck[j]] = [deck[j], deck[i]]
}
```i down from 51 to 1 (i-- takes 1 off).Math.random() * (i + 1) is a number from 0 to just under i + 1; Math.floor cuts the decimals: a whole
number from 0 to i.[deck[i], deck[j]] = [deck[j], deck[i]] swaps two cards in one line. The ; in front stops JavaScript from
gluing this line (it starts with [) onto the line before.In newDeck, between the for line that builds the deck and return deck, write the shuffle loop.
Skills: Arrays and objects, Loops
← A deck of 52 Piles in one object →