Suppose I have a list of strings. How do I generate a random one?
Asked
Active
Viewed 7,989 times
4
-
4If you need to get random strings in a non-duplicative manner (not specified above), consider using a "shuffle" such as a Fisher-Yates. (After the shuffle you can just 'shift' off the front of the Array.) – Dec 14 '10 at 01:23
-
possible duplicate of [Getting random value from an array](http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array) – user Feb 04 '15 at 00:30
4 Answers
21
You mean, get a random array member?
var strings = ['a', 'b', 'c'];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
If you mean a random string, it is a little different.
var randomStrLength = 16,
pool = 'abcdefghijklmnopqrstuvwxyz0123456789',
randomStr = '';
for (var i = 0; i < randomStrLength; i++) {
var randomChar = pool.charAt(Math.floor(Math.random() * pool.length));
randomStr += randomChar;
}
Of course, you can skip the pool
variable and do String.fromCharCode()
with a random number between 97 ('a'.charCodeAt(0)
) and 122 ('z'.charCodeAt(0)
) for lowercase letters, etc. But depending on the range you want (lowercase and uppercase, plus special characters), using a pool is less complex.

alex
- 479,566
- 201
- 878
- 984
-
Wouldn't using Math.ceil() there cause one never to select the first element (0)? – Andrew Barber Dec 14 '10 at 01:09
-
@Andrew Barber: Not never, but extremely seldom. You would get a distribution over four indexes, where the first occurs only when the random number is exactly zero. – Guffa Dec 14 '10 at 01:13
-
@Guffa: extremely seldom -- you mean on an average 20% of the time ? – Mahesh Velaga Dec 14 '10 at 01:15
-
-
2
-
@Guffa: Its a little tricky I think, what happens when the array size is low ? lets say 5 and what if the random number generated is less than 0.2 (which will be on an average 20% of the time)? – Mahesh Velaga Dec 14 '10 at 01:24
-
@Mahesh Velaga: The index will only be 0 for the random number 0.0, but for any value 0.0 < n <= 0.2, the index will be 1. For example `Math.ceil(0.0000000001*5) = 1`. – Guffa Dec 14 '10 at 01:31
-
@Guffa: Sorry, my bad .. I started off with taking ceil in my mind and in between I switched to floor, thanks for patiently answering my non-sense questions :) – Mahesh Velaga Dec 14 '10 at 01:34
8
Alex and Mahesh are right on, just wanted to demonstrate how I might implement their solutions if I felt like living dangerously. Which I do.
Array.prototype.chooseRandom = function() {
return this[Math.floor(Math.random() * this.length)];
};
var a = [1, 2, 3, 4, 5];
a.chooseRandom(); // => 2
a.chooseRandom(); // => 1
a.chooseRandom(); // => 5

maerics
- 151,642
- 46
- 269
- 291
2
var randomString = myStrings[Math.floor(Math.random() * myStrings.length)]

Guffa
- 687,336
- 108
- 737
- 1,005

Mahesh Velaga
- 21,633
- 5
- 37
- 59