Retrieve Random Item from an Array in Javascript

Retrieve Random Item from an Array in Javascript

ยท

3 min read

hashnode.png Retrieve a random item from an array is a common task and fairly easy to implement. There are many ways to achieve that and I am going to discuss a few of them

So let's figure out how to accomplish it.

Here, Firstly we create an array using the array literal syntax( [ ] ).

const fruits = ["Apple", "Banana", "Avocado", "Blackberries", "Grapes"];

Methods to get a random item from an array

common Method

In the normal method, we are using Math.random() function to generate a number between 0โ€“1 (inclusive of 0, but not 1) randomly.

const random = Math.random();

Now, we can get the total length of the fruits array.

const totalFruits = fruits.length

Then multiply the random number with the length of the array.

const randIndex = Math.floor(random * totalFruits)

In the above code, we used Math.floor() function to result to make it a whole number.

Now we get the random item by using randIndex

const randomFruits = fruits[randIndex]

Here we can write the above code in a single line.

const random = fruits[Math.floor(Math.random() * fruits.length)]; 

console.log("Random Fruit:", random); // => Random Fruit: Banana

Instead of using Math.floor() we can also use ~~. It is much faster than the Math.floor(). So when it comes to performance optimization while producing output using UI elements. ~~ wins the game.

var random = fruits[~~(Math.random() * fruits.length)];

console.log("Random Fruit:", random);  // => Random Fruit: Banana

But if you know that the array is going to have millions of elements then you might want to reconsider between the bitwise operator and Math.floor(). as bitwise operator behave weirdly with large numbers because it clamps to a 32-bit integer. See the below example explained with the output.

const number = Math.floor(14444323231.2); // => 14444323231

const number = 14444323231.2 | 0; // => 1559421343

By underscore.js and lodash.js

If you have already got underscore & lodash included in your project you can use _.sample

const random = _.sample(fruits);

console.log("Random Fruit:", random); // => Random Fruit: Blackberries

The above method will return one item randomly from the array. If you want to get one or more random item from an array then you can pass one more argument in underscore

const random = _.sample(fruits, 2);

for lodash use a _.sampleSize method

const random = _.sampleSize(fruits, 2);

Prototype Method

We can make an array prototype sample

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

Now:

const random = fruits.sample()

console.log("Random Fruit:", random); // => Random Fruit: Blackberries

Thanks for reading ๐Ÿ˜„. If there is anything I have missed, or if you have a better way to do it, then please let me know.

let's connect on Twitter .