DEV Community

Discussion on: Simple snippet to shuffle array

Collapse
 
bravemaster619 profile image
bravemaster619

WARNING why you shouldn't use this method in cryptographic functions: javascript.info/task/shuffle

That somewhat works, because Math.random() - 0.5 is a random number that may be positive or negative, so the sorting function reorders elements randomly.

But because the sorting function is not meant to be used this way, not all permutations have the same probability.

Collapse
 
gabrielrufino profile image
Gabriel Rufino

Thanks for contribute. 🙂

Collapse
 
pentacular profile image
pentacular

It also breaks down when there are key collisions.

Sorting by non-unique keys is not shuffling.

Fisher-Yeats is trivial to implement and theoretically correct -- use that instead.