Guides

How to shuffle an array in JavaScript — and why sort with Math.random cheats

Illustration: a row of cards, two of them swapping places in mid-air

You're building a quiz and ask an AI to shuffle the questions. It writes one elegant line:

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

It works. The order is different every time. But we ran that line two hundred thousand times on a five-item list. The first item stayed in first place 32% of the time. It should be 20%. On a ten-item list — almost 20% instead of a fair 10%.

So your first question shows up first one and a half to two times more often than the rest. Players will notice before you do. Let's shuffle fairly — it's five steps and ten lines.

Why sort shuffles unfairly

sort is sorting. It compares pairs of items and expects an answer to "which of the two is bigger". And it expects the answers to be consistent: if A is bigger than B and B is bigger than C, then A is bigger than C.

Instead of an answer, we hand it a coin toss. Sorting isn't built for that. Its internal order of comparisons pulls some items forward more often than others. The result looks chaotic, but it's skewed — and the skew even depends on the browser.

The fair method was invented back in 1938. It's called the Fisher–Yates shuffle.

How to shuffle an array: step by step

  1. Make a copy. The shuffle will change the array in place. So the original list of questions isn't ruined, work on a copy:

    const result = [...questions]
    
  2. Walk from the end of the list to the start. You need a plain loop that starts at the last item and stops at the second:

    for (let i = result.length - 1; i > 0; i--) {
    
  3. Pick a random spot between the start and the current position. Not across the whole list — only among the items not shuffled yet, from 0 to i inclusive. Math.floor matters here: why not Math.round is explained in what is a random number.

      const j = Math.floor(Math.random() * (i + 1))
    
  4. Swap the two items. The current one and the randomly picked one. In JavaScript that's one line:

      [result[i], result[j]] = [result[j], result[i]]
    }
    

    That's the whole secret. At each step the last "unshuffled" item gets a random partner and freezes in place. As if you were pulling a random card from the deck and laying it on a new pile.

  5. Wrap it in a function. In full it looks like this:

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

    The semicolon before the square bracket isn't a typo. Without it JavaScript may glue the line to the previous one. If your project has an auto-formatter, it will add it for you.

Check that the shuffle is fair

Don't take it on faith — not from us, not from AI. The check takes a minute. Paste this into the browser console:

const hits = [0, 0, 0, 0, 0]
for (let n = 0; n < 100000; n++) {
  const first = shuffle([0, 1, 2, 3, 4])[0]
  hits[first]++
}
console.log(hits)

The code shuffles the list a hundred thousand times and counts which item ended up first. With a fair function all five numbers land around 20,000. Swap in the sort version instead of shuffle — and watch the numbers spread apart.

What you get

You'll have a shuffle function you can call anywhere:

const quiz = shuffle(questions)          // shuffled questions
const hand = shuffle(deck).slice(0, 5)   // five random cards, no repeats

The second example is especially handy: "pick N random items without repeats" is exactly "shuffle and take the first N". The original array stays untouched.

And you can give the AI a short rule in your prompt: "for shuffling use Fisher–Yates, not sort with Math.random". The model knows the algorithm and will write it — it just doesn't always remember to on its own.

Can I just use lodash?

You can: the lodash library has a ready-made shuffle, and it's fair. But pulling in a whole library for ten lines is overkill. The function above does the same thing.

Is this good enough for a prize giveaway?

For a game or a quiz — yes. For a giveaway with money or prizes, replace Math.random with the cryptographic generator crypto.getRandomValues: its output can't be predicted.

Why does the shuffled list sometimes match the original?

Because that's one of the possible outcomes too. Five items have 120 possible orders, and the original one comes up about once in 120 shuffles. If it never happens, the shuffle is the unfair one.

Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →