How To Correctly Shuffle An Array in JavaScript

“randomly” sorted
array.sort(function (a, b) { return 0.5 — Math.random() })

The Correct Way — Fisher-Yates Algorithm

 — To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
j ← random integer such that 0 ≤ j ≤ i
exchange a[j] and a[i]
for(let i = array.length — 1; i > 0; i--){
const j = Math.floor(Math.random() * i)
const temp = array[i]
array[i] = array[j]
array[j] = temp
}

Final Thoughts

--

--

--

Software Developer and Internet Marketer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nitin Patel

Nitin Patel

Software Developer and Internet Marketer

More from Medium

JavaScript Utility Methods in Detail

4 Ways to Handle Async Operations in Javascript

4 Ways to Handle Async Operations in Javascript

JavaScript Algorithms: Maximum Subarray (LeetCode)

Open-source & Javascript| Software engineering apprenticeship pattern 📚