Javascript Pick Random from Array

Javascript Pick Random from Array – This article includes the various methods by which you can pick a random element from an array in Javascript. There are many methods by which you can do this.

There is always a case in programming when we need to find the random value from an array. For this purpose, Javascript provides various inbuilt methods by which you can easily pick up any random elements in the array. So without wasting more time, let’s dive in and learn.

Also Read: Difference between Javascript Slice v/s Splice

Random Elements from Array in Javascript

You can pick the random element from an array by using any of the following given methods provided in Javascript.

Using Math.random() and Math.floor() Method to pick random from an array

You can easily find out the random element from an array using the above two methods. The steps for doing this are as follows:

  1. Use Math.random() function to get the random number between(0-1, 1 exclusive).
  2. Multiply it by the array length to get the numbers between(0-arrayLength).
  3. Use Math.floor() to get the index ranging from(0 to arrayLength-1).

Here is an example code showing the above approach i.e to pick random from a javascript array.

var arr = ["Alex", "Jake","Logan", "Mark"]; 
var randomElement = arr[Math.floor(Math.random() * arr.length)];

Using random(a, b) Method to pick random from an array

Here is another method that is also very popular when it comes to finding out or picking the random element from Array in Javascript. This method includes the use of random() method.

Here is the formula for finding random elements from an array in javascript.

Math.floor(Math.random() * (1 + High - Low)) + Low;

All you need to do is to follow these three basic steps:

  1. The random(a, b) method is used to generates a number between(a to b, b exclusive).
  2. Taking the floor value to range the numbers from (1 to array length).
  3. Subtract 1 to get the index ranging from(0 to array length-1).

All you need is a high number and a low number to define the range of numbers you want. But we are working with arrays, so the position of an item in an array is based on an index number. This index number starts at 0 and increments by one until you hit the end of the array, which will be our high point.

Here is the example of the same

var myArray = ['January', 'February', 'March'];    
var rand = myArray[Math.floor(Math.random() * myArray.length)];

So, this is all about how we pick random from arrays in Javascript. Thanks for reading!

Leave a Comment