Explain Codes LogoExplain Codes Logo

Get a random item from a JavaScript array

javascript
randomness
performance-optimization
array-manipulation
Nikita BarsukovbyNikita Barsukov·Aug 26, 2024
TLDR

Directly fetch a random array item by marrying Math.random() with the anticipated array length:

const randomItem = (array) => array[Math.floor(Math.random() * array.length)];

With this, we take up a perfectly random index ensuring each item gets equal representation.

Multiple considerations for a superior result

While our direct answer is apt in numerous forms, certain cases demand a tad more sophistication. Hereunder, we're exploring a few such instances.

Confirming equal opportunity for each item

Working with petite arrays or when distribution carries weight, authenticating that Math.random() offers fair probability to each item becomes paramount. Beware, randomness can carry a bias, often going unnoticed.

Handling humongous data sets

For enormously larger arrays, performance becomes critical. Though Math.random() and Math.floor() are real lightweights, when handling gargantuan datasets or performance-sensitive apps, exploring bitwise operations (e.g., | 0, ~~) can get you a faster integer rounding.

// Getting jiggy with bitwise operation. const randomItem = (array) => array[(Math.random() * array.length) | 0];

Cycling through arrays with style

A well-crafted reusable function can save hours while enhancing code's readability. Be it strings, numbers, or complex objects, this getRandomItem function reaps benefits aplenty.

function getRandomItem(array) { // Everybody loves the DJ. Let's spin that wheel of fortune! return array[Math.floor(Math.random() * array.length)]; }

Spoiling the prototype for some good

Consider adding this slice of genius to the Array.prototype if you dig using this functionality over sundry projects. But caution! Modifying in-built prototypes can unfold as unexpected behaviour.

A quick peep into services and libraries

For niche needs and sophistication, considering third-party libraries has its merits. Powerhouses like Lodash and Underscore bring to the table utility methods such as _.sample and _.shuffle that expertly handle random selections and array shuffling.

// Because sampling is not just for DJs. const randomItem = _.sample(array);

Remember, our objective is to use such libraries judiciously, assessing the overhead they may sneak in.

Serving uniqueness on a silver platter

If your goal is to save essentially unique random elements (avoiding repetition), you could jolly well consider shuffling the array or maintaining a record of picked indices. For such cases, a Fisher–Yates shuffle (also known as the Knuth shuffle) makes a fine choice, bearing a low complexity.

Top hats off to alternative rounding methods

The veterans in the field might prefer alternative rounding methods like the double bitwise NOT ~~. While it fits the bill as an alternative to Math.floor(), remember it's more of a programmers pet and may impact readability for the newbies.

// It's hip to be ~~square~~ NOT. const randomItem = (array) => array[~~(Math.random() * array.length)];