This is a short tutorial on how to get a random value from a JavaScript array. To do this, we will have to generate a random index number that represents an element in the array.
Let’s jump straight into an example:
//A function that returns a random element //from a JavaScript array. function getRandomArrayElement(arr){ //Minimum value is set to 0 because array indexes start at 0. var min = 0; //Get the maximum value my getting the size of the //array and subtracting by 1. var max = (arr.length - 1); //Get a random integer between the min and max value. var randIndex = Math.floor(Math.random() * (max - min)) + min; //Return random value. return arr[randIndex]; } //Example JavaScript array containing various types of animals. var exampleArray = new Array( 'Dog', 'Cat', 'Horse', 'Penguin', 'Lion', 'Tiger', 'Zebra' ); //Get a random value from our array. var animal = getRandomArrayElement(exampleArray); //Log it to the console. console.log(animal);
In the JavaScript code above, we created a custom function called getRandomArrayElement(). This function takes in an array as a parameter and returns a random element.
Inside this function:
- We set the minimum number to 0. This is because arrays indexes start at 0.
- Using the length property, we worked out what the last index will be. This is our maximum number.
- Once we figured out the minimum and maximum value, then generated a random integer value between the minimum and maximum values. To do this, we used theĀ Math.floor() method andĀ Math.random() methods.
- Finally, we returned the array value that corresponds to the integer that we generated.
For the sake of this example, I created a JavaScript array containing different types of animals. If you run the code, you will see that a random animal name is logged to the console each time.
And that’s it!