Proposal: Array.prototype.shuffle (Fisher-Yates)

John Terenzio john at terenz.io
Thu May 16 14:02:59 PDT 2013


Many scripting languages, such as Ruby, PHP, and Python (via the random
module), have a built-in for properly shuffling an array. I propose adding
Array.prototype.shuffle to the ES spec. I think it should act like
Array.prototype.reverse, shuffling the array in place and returning a
reference to it. It should use the Fisher-Yates algorithm. See
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Since this functionality is missing, some less-seasoned developers fall
into the trap of using the "sort by random" method, which produces bias.
See
http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/

In a perfect world, this would use a better random number generator than
the existing Math.random, but for now an implementation like the one below
would still be a vast improvement over having to implement manually and
possibly incorrectly. See
https://bugzilla.mozilla.org/show_bug.cgi?id=322529

Example implementation:
https://gist.github.com/jterenzio/28bb972f3abb7618b14b

I don't think adding this to the spec would cause many compatibility issues
and the implementation should be very straightforward. Let me know what you
think!

Best,
John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20130516/f56b647b/attachment.html>


More information about the es-discuss mailing list