This page explains how to randomize an array.

- pick a random item
- swap it with the last element
- now the last item is “shuffled”
- pick a random item from the “unshuffled” items (any except the last 1)
- swap it with the 2nd to last element
- now the 2nd to last item is “shuffled”
- repeat until each item has been swapped with a random remaining item

The process involves swapping values in the array. If you have 2 variables, `a`

and `b`

, what commands would you use to swap their values?

```
a = b;
b = a;
```

This does not quite work. Let’s see what happens if we start with `a = 5`

, and `b = 10`

.

`a = b`

means `a`

is now 10. Then we run `b = a`

and we get `b = 10`

because `a`

was just set to 10. That leaves us with `a = 10`

and `b = 10`

.

We need to temporarily store the original value of `a`

in another variable. You can think about this as having an apple in one hand and a banana in the other. If you aren’t allow to juggle them, and each hand can only hold 1 item at a time, then you need to set one of the fruits down on a table to free up one of your hands. You can set the apple on the table, put the banana in the apple-hand, then pick up the apple from the table with your banana-hand.

`t = a;`

table gets the apple

`a = b;`

apple-hand gets the banana

`b = t;`

banana-hand gets the apple off the table

This code will work in the playground, except it’s missing the `.length`

key. If you know the number of elements in your array, you can substitute the number. The details are a little tricky because you have to remember that arrays start numbering from 0, and the `pickRandom()`

function (which is a custom function) picks a number starting from 1. That’s why there’s a `+1`

and a `-1`

in the `rando`

value.

```
let deck = [1, 2, 3, 4, 5];
for (let i = deck.length-1; i > 0; i--) {
let temp = deck[i];
let rando = pickRandom(i+1)-1;
deck[i] = deck[rando];
deck[rando] = temp;
}
```

Edit:

In modern JavaScript, you can swap values without creating your own `temp`

variable.

```
[deck[i], deck[rando]] = [deck[rando], deck[i]]
```

You can even do it with more than 2 variables.

```
let a = 1;
let b = 2;
let c = 3;
let d = 4;
[a,b,c,d] = [d,a,b,c]
```

This will result in:

`a === 4`

`b === 1`

`c === 2`

`d === 3`

–Frankie