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:
- Use Math.random() function to get the random number between(0-1, 1 exclusive).
- Multiply it by the array length to get the numbers between(0-arrayLength).
- Use Math.floor() to get the index ranging from(0 to arrayLength-1).
var arr = ["Alex", "Jake","Logan", "Mark"]; var randomElement = arr[Math.floor(Math.random() * arr.length)]; console.log(randomElement) //Output Alex
Using random(a, b) Method to pick random from an array
Math.floor(Math.random() * (1 + High - Low)) + Low;
All you need to do is to follow these three basic steps:
- The random(a, b) method is used to generates a number between(a to b, b exclusive).
- Taking the floor value to range the numbers from (1 to array length).
- 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)];