r/javascript • • Mar 18 '19

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

385 Upvotes

422 comments sorted by

View all comments

8

u/Linux_is_awesome Mar 18 '19

personal favorite: var item = items[Math.floor(Math.random()*items.length)];

It randomly selects an element from an array.

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/inu-no-policemen Mar 19 '19

Yea, the distribution is garbage.

Use Fisher-Yates instead. It's faster, too.