How to choose a random array element from an associative array with respect to the length of the array?
For example:
actors[name]=firstname movielist[title]=[director,artwork,actors]
If I wanted to remove a single random element and all of its information, how can I reach it?
The answer
By assuming by "associative array" you hear a JavaScript object (which has zero or more key / value properties), you can do something like the following, which selects a random property and returns its name:
function getRandomObjectPropertyName(obj) { var a = [], k; for (k in obj) if (obj.hasOwnProperty(k) a.push(k); if (a.length === 0) return null; // or whatever default return you want for an empty object return a[Math.floor(Math.random() * a.length)]; // or to return the actual value associated with the key: return obj[ a[Math.floor(Math.random() * a.length)] ]; }
In case it is not clear how it works above, it copies all the key names of the object into an array. The use of
.hasOwnProperty()
is (probably) optional according to your needs. Because the array has a length and digitally indexed elements, you can then use the Math functions to randomly select an element.Once you have the name of the randomly selected key, you can use it to access the value of that property. Or (as indicated above), you can change the function to return the actual value. Or (not shown, but trivial) modify the function to return the key and the value as a new object. Up to you.
It is unclear to your question what your data structure is but assuming that
movielist
is an object where each property has a key name that is the title of the movie and an associated property that is an array containing the director, illustration and a nested range of actors, then you can do it: var randomMovieTitle = getRandomObjectPropertyName(movielist); // randomMovieTitle might be, say, "Back to the future" // you could then get the list of actors associated with the movie like so: var actorsFromRandomMovie = movielist[randomMovieTitle][2]; // or get the director: alert(movielist[randomMovieTitle][0]); // "Robert Zemeckis"
0 Response to "Choosing a random array element from an associative array"
Posting Komentar