How would I pick a random array element from an associative array with regards to array length ?
For example:
actors[name]=firstname
movielist[title]=[director,artwork,actors]
If I wanted to pull out a single random array element and all the information it from it then how would I achieve this?
Assuming by “associative array” you mean a JavaScript object (which has zero or more key/value properties), you can do something like the following, which selects a property at random and returns its name:
In case it’s not clear how the above works, it copies all of the key names from the object into an array. Use of
.hasOwnProperty()is (arguably) optional depending on your needs. Because the array has a length and numerically indexed items you can then use the Math functions to select an item randomly.Once you have the randomly selected key name you can use it to access the value of that property. Or (as shown above) you could change the function to return the actual value. Or (not shown, but trivial) change the function to return both key and value as a new object. Up to you.
It’s kind of unclear from your question what your datastructure is, but assuming
movielistis an object where each property has a key name that is the movie title and an associated property that is an array containing the director, artwork and a nested array of actors, then you can do this:EDIT: If you don’t care about older browsers you can use
Object.keys()to get an array of all the key names and then randomly select from that.