Pick Random Array Item in JavaScript
- 1 minute read
This simple JavaScript snippet accepts an array and returns a random item from it, using the good old Math.random method:
const randomItem = (arr) => {
return arr[Math.floor(Math.random() * arr.length)];
};
To use it, just pass in an array:
const arr = [`dog`, `cat`, `bird`, `fish`, `dinosaur`];
const item = randomItem(arr);
After the code in the above snippet has executed, item
will equal one of the strings from arr
.
And I’ll leave you with a one-liner variant of randomItem
with the same functionality:
const randomItem = (arr) => arr[Math.floor(Math.random() * arr.length)];
Conclusion
Anyway, that’s all you need to start randomly picking items from your JavaScript arrays. Enjoy!