Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random element from associative array in javascript?

Tags:

javascript

I am building a playlist of songs in javascript. I have used an associative array foo -- the structure of my object looks akin to:

foo[songID] = songURL;

I am trying to build in shuffling functionality. I would like to select a song at random from this list. Is there a simple way to do this -- the array is not indexed.

like image 829
Sean Anderson Avatar asked Jan 23 '12 03:01

Sean Anderson


Video Answer


1 Answers

You can use the function Object.keys(object) to get an array of the keys of an object. Very good documentation for this function can be found at MDN.

You also seem to have two different but related questions.

Your topic asks how to get a random element from an object. For that,

var randomProperty = function (object) {
  var keys = Object.keys(object);
  return object[keys[Math.floor(keys.length * Math.random())]];
};

But you also ask in the body of your question how to shuffle the array. For that, you'll want a shuffle function of some sort (most probably an implementation of Fischer-Yates), and do that directly.

var objectKeysShuffled = function (object) {
    return shuffle(Object.keys(object));
};
like image 118
Havvy Avatar answered Oct 30 '22 12:10

Havvy