Getting a random item from a JavaScript array is an operation that we’ve to do sometimes.
In this article, we’ll look at ways to get a random item from a JavaScript array.
Math.random
We can use the Math.random
method to return a random index from an array.
Then we can use that to get an element from the array.
For instance, we can write:
const items = [1, 2, 3]
const item = items[Math.floor(Math.random() * items.length)];
Since Math.random
returns a number between 0 and 1, we’ve to multiply the returned number by items.length
to get an index.
Also, we’ve to use Math.floor
to round the number down to the nearest integer to get an index.
Lodash
Lodash has various handy methods we can use to get a random item from an array.
The sample
method lets us get a random item from an array.
For instance, we can write:
const items = [1, 2, 3]
const item = _.sample(items);
console.log(item)
We just pass in the array we want to get an item from as the argument.
Also, we can use the random
method to pick a random number from 0 up to the given number.
For instance, we can write:
const items = [1, 2, 3]
const item = items[_.random(items.length - 1)]
console.log(item)
We just pass in the max number in the range we want to get.
Also, we can shuffle the entire array and pick the first item from the shuffled array.
To do this, we can use the shuffle
method.
For example, we can write:
const items = [1, 2, 3]
const [item] = _.shuffle(items)
console.log(item)
We call shuffle
with the items
array to return a shuffled version of the items
array.
Then we get the first item with destructuring.
Shuffle with sort
We can also shuffle arrays with sort
.
For instance, we can write:
const items = [1, 2, 3]
const [item] = items.sort(() => 0.5 - Math.random())
console.log(item)
to shuffle the array by calling sort
with a callback that returns a number between -0.5 and 0.5.
This lets us shuffle an array since items are swapped when the returned number is positive.
Conclusion
There’re several ways to get a random item from a JavaScript array.
We can either use native JavaScript methods.
Or we can use convenience methods from Lodash to help us.