Get random element from an array (JavaScript)
function randomItem(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
randomItem(['a', 'b', 'c']); // 🤷 'a' or 'b' or 'c', it's random
How does it work?
- Get a random number between 0 and 1 with
Math.random
. It can return 0 but never 1. - Multiply the random number from point 1 by the number of items on the array.
- Use
Math.floor
to remove the decimal part.
Notice that you cannot use Math.round
instead of Math.floor
because
it could round up and return an array index out of bounds.
How could someone come up with this solution?
The Math.random
method can return all the values between 0
and almost 1
.
What happens if we floor it? We can only get the value 0
.
OK, but let's say we have a list with 10 elements?
In that case we need values between 0
and 9
.
If we multiply Math.random
by 10
we get values between 0
and almost 10
.
If we floor it we get the integers from 0 up to 9:
Note: On the previous charts the x axis are tries, y axis are all the possible random values. We have to assume we selected and sorted the tries to get all the possible random values.
Learn more about discrete vs continuous values.
Questions
What's the function f output?
function f(items) {
return items[Math.floor(Math.random() * items.length)];
}
f([1, 2, 3]);