0

How to select/get random word from list using JavaScript?

16th Nov 2020, 4:39 AM
Rb King
Rb King - avatar
2 Answers
+ 2
You need a random index, and for that you would use Math.random(), but it gives a number between 0 and 1 only, so we multiply it by the length of array, lets suppose 4 is the length Math.random() * 4 would give us a number between 0 and 4 but we need the integer version, not decimal one, so we need to use Math.floor() to bring lets suppose 3.932 to just 3. let random_index = Math.floor(Math.random() * arr.length) console.log( arr [ random_index ] )
16th Nov 2020, 6:41 AM
maf
maf - avatar
+ 1
To select a random list element you need a random integer index i (0<=i<length). We have function Math.random() that returns a random floating point number m, 0<=m<1. So you can just multiply the returned value by length, and take integer part (for example with Math.floor) Depending on your application you might need better implementations of random (more secure, better equidistributed, or just having better control over inner state - if that's the case you should search for javascript random number libraries with the properties you need)
16th Nov 2020, 6:33 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar