How To Shuffle An Array in JavaScript

Fisher-Yates Algorithm

Most of the answers on StackOverflow on how to shuffle an array are not truly random.

I wanted to repost this, so we never lose it. Using this algorithm from 1938 we can shuffle an array with more true randomness than other options out there.

JavaScript implementation

Here's the JavaScript version of the algorithm using ES6.

 * @param {Array} array
 * @return {Array}
export function randomizeArray(array = []) {
  if (array.length === 0) return array

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

    array[i] = array[j]
    array[j] = temp

  return array
}Code language: PHP (php)

Kudos: Nitin Patel

Leave a Reply

Your email address will not be published. Required fields are marked *