How to shuffle elements in a JavaScript array

By

Published · Updated

Tagged: JavaScript

Shuffle a JavaScript array fairly with the Fisher-Yates algorithm, keep the original unchanged, pick random items, and use crypto when the order must be unpredictable. Plus why sort() with Math.random() is biased.

Use the Fisher-Yates algorithm to shuffle an array fairly:

const shuffle = items => {
  for (let i = items.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    const current = items[i]

    items[i] = items[j]
    items[j] = current
  }

  return items
}

The function changes the array passed to it:

const numbers = [1, 2, 3, 4, 5]
shuffle(numbers)

Pass a copy when you want to keep the original array unchanged:

const numbers = [1, 2, 3, 4, 5]
const shuffled = shuffle([...numbers])

JavaScript has no built-in array shuffle method, so you need a small function like this one, or a library that ships one.

How it works

The algorithm starts at the end of the array. At each step, it swaps the current item with a random item from the part not shuffled yet, including the current item itself.

Math.random() * (i + 1) gives a number between 0 and i + 1, never i + 1 itself. Math.floor() turns it into a whole index from 0 to i.

It goes through the array once, so it’s fast even on large arrays.

You can write the swap in one line with destructuring:

[items[i], items[j]] = [items[j], items[i]]

Don’t use sort() with Math.random()

You’ll see this shortcut a lot:

numbers.sort(() => Math.random() - 0.5)

It does not give every possible order the same chance. sort() expects the comparison to be consistent, and a random answer breaks the assumptions of the sorting algorithm.

I ran it 600,000 times on [1, 2, 3] in Node.js 22. Each of the 6 possible orders should come up about 16.7% of the time. Here’s what I got:

Ordersort() shortcutFisher-Yates
1 2 337.5%16.7%
1 3 26.3%16.7%
2 1 312.5%16.6%
2 3 16.3%16.7%
3 1 26.3%16.7%
3 2 131.2%16.7%

The original order came back more than a third of the time. With 10 items, the first item stayed in first place 19.5% of the time instead of 10%.

The exact numbers depend on the sorting algorithm of each JavaScript engine, but the bias is there. sort() also changes the original array.

A common Fisher-Yates mistake

This version looks almost the same, but it picks the random index from the whole array at every step:

// Biased, don't use
for (let i = 0; i < items.length; i++) {
  const j = Math.floor(Math.random() * items.length)
  ;[items[i], items[j]] = [items[j], items[i]]
}

With 3 items it makes 27 equally likely sequences of swaps, and 27 can’t be split evenly into 6 orders. In my test some orders came up 18.5% of the time and others 14.8%.

The fix is to pick j only from the part not shuffled yet, from 0 to i, like the first function does.

Shuffle without changing the original

If you never want the function to touch its input, copy inside it:

const shuffled = items => {
  const copy = [...items]

  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[copy[i], copy[j]] = [copy[j], copy[i]]
  }

  return copy
}

const numbers = [1, 2, 3, 4, 5]
const result = shuffled(numbers)
// numbers is still [1, 2, 3, 4, 5]

The spread operator makes a shallow copy. The array is new, but if it contains objects, both arrays point to the same objects.

The same trick works on a string, since spreading a string gives you an array of characters:

shuffled([...'hello']).join('')

Pick random items from an array

To pick a few random items without repeats, shuffle a copy and take the first ones:

const pickRandom = (items, count) => shuffled(items).slice(0, count)

pickRandom(['a', 'b', 'c', 'd', 'e', 'f'], 3)

If you only need one random item, you don’t need to shuffle anything. Pick a random index, as I explain in generating a random number between two numbers:

const item = items[Math.floor(Math.random() * items.length)]

When the order must be unpredictable

Math.random() is fine for games and interface effects. It’s not designed to be unpredictable, so don’t use it when someone could gain something by guessing the order, like a raffle or a lottery draw.

Use crypto.getRandomValues() instead. It’s available in browsers and in Node.js as the global crypto object:

const randomInt = max => {
  // Largest multiple of max that fits in 32 bits
  const limit = Math.floor(0x100000000 / max) * max
  const buffer = new Uint32Array(1)

  do {
    crypto.getRandomValues(buffer)
  } while (buffer[0] >= limit)

  return buffer[0] % max
}

const secureShuffle = items => {
  const copy = [...items]

  for (let i = copy.length - 1; i > 0; i--) {
    const j = randomInt(i + 1)
    ;[copy[i], copy[j]] = [copy[j], copy[i]]
  }

  return copy
}

The loop in randomInt() throws away the few values above limit. Without it, % max would make the small numbers a little more likely than the others.

Want me to talk about your product? You can sponsor this site.

Related posts about js: