DEV Community

Discussion on: 20 Killer JavaScript One Liners ☝️

Collapse
 
0826gm profile image
0826gm

Array shuffling this way won't be statistically random, it's biased due to how sort works with non-deterministic compare function. I propose changing the snippet to the similar

const shuffleArray = (arr) => arr.map(e => [Math.random(), e]).sort((a,b) => a[0] - b[0]).map(e => e[1]);
Enter fullscreen mode Exit fullscreen mode

...which assigns a random "position" to each element, compares by those, then discards them.

There are even better ways (O(n)).

For more on this, see stackoverflow.com/q/2450954/8376184

Collapse
 
mellen profile image
Matt Ellen • Edited

This has come up before!

Nice post. Be aware that shuffling an Array like this is not perfectly random and a proper implementation is a little more complicated: medium.com/@nitinpatel_20236/how-t...