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

About Ricard Torres

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

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

*
*