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

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, 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> if you need to.