I have a hashtable full of strings. I believe Javascript arranges the values in an arbitrary order. I want to be able to pull random strings from the hashtable. I’ve searched for ways to pull random elements from a hashtable but have been unsuccessful. Any idea on how to do this?
I never use Javascript, but I know in C# you can use a foreach loop and count through it similar to a for loop. This is off the top of my head:
int target = Random.next(0, myHashtable.Count);
int i = 0;
MyClass returnedValue;
foreach(Key key in myHashtable)
{
if(target == i)
{
returnedValue = myHashtable[key]
break;
}
else
{
i++;
}
}
It’s not particularly elegant, but I think it would do the trick.
Edit: TonyD’s solution is definitely more elegant.
Create an array that contains your keys, randomly read a key from the array, then access the the hashtable with the key.