Getting a random value from a JavaScript array
For a random array item, create a fraction with Math.random()
, scale it up to the array length, and then round down using Math.floor()
to produce a valid index.
This formula picks a randomItem
from arr
:
Math.random()
: Generates the mystery number (a random fraction).arr.length
: Expands the fraction to the size of the array.Math.floor()
: Ensures an integer index (no decimals invited to this party).
Expanding the basics: Randomness at scale
Extracting a single random element from an array is cool, but you know what's even cooler? Being able to re-use this magic and get multiple random elements. Let's dip deeper.
1. The slick lodash way
Lodash library offers two handy functions to serve randomness on a platter:
_.sample(array)
: Single random element. Simple as a Sunday morning._.sampleSize(array, n)
: N random elements. Because more is merrier!
2. Unleashing the power of prototype
Why not add a custom method, randomElement()
, to the Array
prototype?
But remember, with great power, comes great responsibility. Extending native objects like Array
can lead to unexpected results and conflicts with other parts of the code.
3. Shaving milliseconds with bitwise operators
If you're competing for microseconds, use bitwise operators like ~~
instead of Math.floor()
:
But, be warned, if your array is large enough to scare Godzilla, stick with Math.floor()
. Bitwise operations can cause issues with large arrays due to 32-bit integer conversion.
Mastering randomness
Re-running randomness
Running random selection repeatedly? Beware of duplicates. Shuffle your array first with a reliable algorithm like Fisher-Yates, then draw from the start of the shuffled array.
Fully understanding random range
Math.random()
is inclusive of 0, exclusive of 1. Hence, multiply by array.length
without subtracting 1- that's a game of Russian roulette we're not playing here.
Randomness limitations and caveats
Bitwise operations and array prototype extensions are cool, but remember, every tool has its place. Mind the restrictions and potential conflicts. No tool is a silver bullet!
Was this article helpful?