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.

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 }
Code language: PHP (php)

Kudos: Nitin Patel

Leave a Reply

Add <code> Some Code </code> by using this tags.