How to shuffle elements in a JavaScript array

By

Learn how to shuffle a JavaScript array with the Fisher-Yates algorithm, and how to keep the original array unchanged.

~~~

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])

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.

Avoid this common shortcut:

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

It does not give every possible order the same chance. sort() also changes the original array.

Math.random() is fine for games and interface effects. Do not use it when the order must be cryptographically secure.

Tagged: JavaScript ยท All topics
~~~

Related posts about js: