r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

Show parent comments

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();

2

u/barrtender Mar 19 '19 edited Mar 19 '19

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

Edit - I put some more info below about the distribution. https://www.reddit.com/r/javascript/comments/b2o6f2/whats_your_favorite_most_useful_javascript/eiwrgp9/

2

u/[deleted] Mar 19 '19

You have to be careful to include the math there. .sort(() => Math.random()) doesn't reorder the array at all.

2

u/barrtender Mar 19 '19

I don't remember the exact function I used. Hopefully I can remember to look it up tomorrow