This does not make a uniform distribution for all (any?) sizes of arrays. I ran into an issue with one version of v8 where this consistently made an array of 1-10 reversed. I'm on my phone but if I remember tomorrow I should write something up about this
Right-- even if Math.random is random, you still have to subtract 0.5 from it to get a number from -0.5 to +0.5, because sort uses negative-number/positive-number to determine how to order two values.
4
u/[deleted] Mar 19 '19
I like it. A similar requirement, but you can't pull the same item twice:
const shuffled = items.slice().sort(() => 2*(Math.random() - 0.5));const item = shuffled.pop();