To get a random element from an array, we can use the built-in function Math.random()
. The Math.random()
function generates a random floating-point number between 0 and 1.
So, if we generate a random number between 0 and the array’s last index, we can get its elements randomly by using this number as the array index.
See the following example:
const arr = ['apple', 'mango', 'orange', 'banana']; // Generate random number from 0 to 3 let randomIndex = Math.floor(Math.random()*arr.length); // Get random item let randomItem = arr[randomIndex]; console.log(randomItem); // Output: mango
In the above example, we are first generating a random floating-point number between 0 and 1 using the Math.random()
function. Please note that it can return 0 but can never return 1.
console.log(Math.random()); // 0.35 console.log(Math.random()); // 0.94 console.log(Math.random()); // 0.54
Now, these random numbers should be in the range of 0 to arr.length-1. In our case from 0 to 3.
Therefore, we have to multiply these randomly generated numbers with the array’s length:
const arr = ['apple', 'mango', 'orange', 'banana']; console.log(Math.random()*arr.length); // 0.03 console.log(Math.random()*arr.length); // 2.46 console.log(Math.random()*arr.length); // 3.69
But the array’s index can never be a floating-point number. It must be an integer from 0 to the array’s length.
Therefore, we have to convert these floating-point numbers into integer values. To achieve that we can use the Math.floor()
function.
The Math.floor()
function rounds down the given number to its nearest integer. If the number is already an integer value, it makes no changes.
For example:
console.log(Math.floor(4.98)); // 4 console.log(Math.floor(4.43)); // 4 console.log(Math.floor(4)); // 4
In our case, the Math.floor()
function will round down the randomly generated number to its nearest integer value.
const arr = ['apple', 'mango', 'orange', 'banana']; console.log(Math.floor(Math.random()*arr.length)); // 2 console.log(Math.floor(Math.random()*arr.length)); // 0 console.log(Math.floor(Math.random()*arr.length)); // 1
We can use these randomly generated numbers as the array index to get the elements randomly.
Thanks for reading.