Shuffle an array properly

The sort(() => Math.random() - 0.5) trick is biased. Fisher-Yates is just as short and actually random.

SNP 042 #2B4 Filed js gamedev

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

It shuffles in place. Pass a copy if you need the original: shuffle([...cards]).

Why not the sort trick? Sort algorithms assume a consistent comparator; a random one produces some orders more often than others. For a card game that is the kind of bug nobody notices and everybody feels.