Random array using the modern Fisher–Yates shuffle algorithm in JavaScript

How to make sure the randomness is really random.

It might be tempting to use just Math.random() but it will not produce fair results.

const notRandomEnough = (array) => array.sort(() => Math.random() - 0.5);

The Fisher–Yates shuffle algorithm example in JavaScript

The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence—in plain terms, the algorithm shuffles the sequence.

Fisher–Yates shuffle on Wikipedia.

See the example below for JavaScript implementation of the modern Fisher–Yates shuffle algorithm.

/**
 * Shuffle an array using the modern Fisher–Yates shuffle algorithm.
 *
 * https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
 *
 * @param {array} array
 * @returns {array}
 */
function shuffleArray(array) {
  let currentIndex = array.length;

  while (--currentIndex > 0) {
    const randomIndex = Math.floor(Math.random() * (currentIndex + 1));

    [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
  }

  return array;
}

Newsletter

Level up your skills with useful web development & UX tips via e-mail.

Comments

If you have any thoughts, please contact me on LinkedIn or see the contact page for more options.