. Advertisement .
..3..
. Advertisement .
..4..
Your application may require you to get a random element from an array using JavaScript. Luckily, this programming language supports pseudorandom number generation, and you can use this capability to accomplish the task. Read on to find out how.
Get A Random Element From An Array Using JavaScript
Math.random()
To pick a random element of an array, you need some math functions of JavaScript to generate a random index.
The Math.random() function is a pseudorandom number generator that returns a floating-point number. The range of returned values is between 0 and less than 1, meaning that 0 is a possible returned value but not 1.
Implementations of JavaScript must make sure that the random values must have a nearly uniform distribution over this range. The algorithm’s initial seed can’t be reset or chosen by users. It must be selected by the implementation.
Syntax:
Math.random()
Note that random numbers generated by the Math.random() function aren’t cryptographically secure. Don’t use them for any applications of sensitive nature. Opt for more secure algorithms, such as window.crypto.getRandomValues() instead.
Though the degree of randomness provided by this function should be enough for our intention here, we can’t use its raw output as the index of the returned element.
Math.floor()
The random() function produces floating-point numbers (based on IEEE 754). They are not integers, which are valid indexes of array elements. On top of that, it generates random numbers over a fixed range (from 0 to less than 1). Meanwhile, the range we need is between 0 and less than the length of our array.
To fix these issues, we need to rely on the Math.floor() function:
Math.floor(x)
This function returns the biggest integer that is equal to or less than the x argument.
This is how you can combine random() and floor() to get a random element from an array:
const sites = ['ITTutoria', 'Reddit', 'Quora', 'Stack Overflow'];
function getRandomElement(arr) {
const max = arr.length;
const index = Math.floor(Math.random() * max);
return arr[index];
}
for (i = 1; i <= 4; i++) {
console.log(getRandomElement(sites));
}
Output:
ITTutoria
Stack Overflow
Reddit
Stack Overflow
Since random() only produces values between 0 and 1, we need to scale them up by multiplying them by the length of the array. This should generate random floating-point numbers between 0 and the length.
To map these numbers to available indexes, we use the floor() function to round them to the largest integer less than or equal to those floating-point values.
In the example above, we have also put the code in a function to make sure it can be reused without hassles. And the for loop allows us to repeat it any number of times we want.
Other Rounding Functions
JavaScript comes with many other functions for different rounding algorithms, such as round(). It can be used to round to two decimal places, for instance.
However, the Math.round() function rounds a value to its nearest integer. The returned value can go up or go down – something we can’t control. In fact, this will affect the uniform distribution provided by random(). That is why we use Math.floor(), not Math.round(), for this task.
Note: we can’t use the Math.ceil() function either, even though it also has the rounding ability.
Since ceil() does the opposite job of floor() and returns the smallest integer that is bigger or equal to the argument, the outputs will range from 1 to the length of the array. The program will ignore the first element (0) and even return the undefined value when the index equals the array’s length.
Example:
function getRandomElement(arr) {
const index = Math.ceil(Math.random() * arr.length);
return arr[index];
}
Output:
Stack Overflow
undefined
Reddit
Quora
Summary
You can combine two math functions to get a random element from an array using JavaScript: Math.random() and Math.floor(). They can generate random indexes for your array with an acceptable uniform distribution.
Leave a comment