简体   繁体   中英

Picking a random array element from an associative array

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:

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'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 movielist is 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:

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM