Javascript

How to choose random element from array in Javascript

Question – How to choose a random element from an array in Javascript?

This tutorial will show how can you choose a random element from an array in JavaScript. You can also get to know the different methods for doing the same.

Javascript choose random from Array

We will go through two different method by which we can easily pick a random element from an array. So let’s get started.

Using the Random(a, b) method

We will use the random() method available in Javascript to find a random number. Random() method takes two inputs a and b which refers to the starting number and the ending number i.e the range in which you want to generate the random numbers.

In this case, we will take the value of starting number as 0 and the ending number as the length of the array. When a random number is generated, we need to take the floor value to range the numbers from (1 to array length). Here is an example of the same.

var rand = myArray[Math.floor(Math.random() * myArray.length)];

Using the lodash Library

Lodash is a very JavaScript library which provides utility functions for common programming tasks. It uses the functional programming paradigm. You can use the sample method provided by lodash to choose randomly from an array. Here is an example.

_.sample(['January', 'February', 'March']);

So this is all about the Javascript choose random from array. Thanks for reading!

Leave a Comment