Pick a random element from an array in JavaScript
In this tutorial, we will learn how to pick a random element from an array in JavaScript. It is essential to know because this is a very common type of operation you will do with the array. For example generating random numbers from 1 to 6 for a dice game, selecting random numbers, etc.
To do this task you need to know the following methods in JavaScript:
- Math.random(): returns a random number between 0 and 1,1 is not included.
- Math.floor(): rounds down the number and returns the largest integer equal to or less than a given integer.
- array.length: it returns the number of elements in the array.
Steps to follow:
- Define the array and pass it to function
random_no
. - We use
Math.random()
to generate a random number and then we multiply with array length to get a number between (0-array length). - Later we use
Math.floor
to get the nearest integer value. - var
random_number
is then used to access the random index of the array.
Example:
function random_no(numbers) { // get random number var random_number = Math.floor(Math.random() * numbers_array.length); // access the element const element = numbers_array[random_number]; return element; } const numbers_array = [122, 202, 985, 889]; const result = random_no(numbers_array); const result2=random_no(numbers_array); console.log(result); console.log(result2);
OUTPUT: 985 202
Hence, every time we run the function a random element is generated.
Leave a Reply