DEV Community

Discussion on: Get a Random Element from an Array in JavaScript

Collapse
 
pengeszikra profile image
Peter Vivo

You are right, maybe with | 0 can write shorter:

const pick = list => list[list.length * Math.random() | 0];

const winner = pick(participants);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gaelgthomas profile image
Gaël Thomas

Oh, I like the idea! I just tried it, and it seems to work well! Thanks for sharing that! 🙏

I also like the idea of creating a generic function to get a pseudo-random value from a list.