How to select a random element from an array in JavaScript
๐
June 28, 2021
๐JavaScript
Today, we will show you how to select a random element from an array in JavaScript with example.
- How to convert the local time to another timezone in JavaScript
- JavaScript array methods Push, Pop, Shift and Unshift
- JavaScript Spread Operator
- How to convert an Array to a String in JavaScript
- Difference between var, let and const in JavaScript
var colors = [
'Yellow',
'Blue',
'Pink',
'Red',
'Black',
'White',
'Green'
];
var color = colors[Math.floor(Math.random() * colors.length)];
console.log(color);
// Output: Pink
How it works:
First, Use the Math.random()
function to get index of array that returns a random value between 0
and 1
.
var rand = Math.random();
// Output: 0.8517781809554954
Now, using the length property we can get the last index of array that is maximum number.
var totalColors = colors.length;
// Output: 7
Then multiply the random number with the length of the array and round down that result by Math.floor
.
var randIndex = Math.floor(Math.random() * colors.length);
// Output: 2
Finally, using random index we can get a random value from array.
var randColors = colors[Math.floor(Math.random() * colors.length)];
// Output: Pink
If you run this code, you will see the random colour name every time.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!