Question: How to get random value from array in javascript
Answer: Sometimes we need to fetch a random value from an array, we are sharing three methods with you to extract random value from the array. You can see the live demo, the button is below.
01. Method
Using 'Math.floor()' Function.
const colors = ["Red", "Green", "Black", "Yellow", "Blue", "Orange", "White"]; const random = Math.floor(Math.random() * colors.length); console.log(random, colors[random]);
Output: Your and our answer may or may not match as it is randomly generated
6 "White" 1 "Green"
02. Method
Using 'Array.prototype' concept.
const colors = ["Red", "Green", "Black", "Yellow", "Blue", "Orange", "White"]; Array.prototype.randomValue = function(){ return this[Math.floor(Math.random()*this.length)]; } console.log(colors.randomValue());
Output: Your and our answer may or may not match as it is randomly generated.
"Red" "White"
03. Method
Using 'find()' function.
const colors = ["Red", "Green", "Black", "Yellow", "Blue", "Orange", "White"]; var randomValue = colors.find((_, i, colors) => Math.random() < 1 / (colors.length - i)); console.log(randomValue);
Output: Your and our answer may or may not match as it is randomly generated
"Green" "Blue"
We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.
Comments
Post a Comment