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.
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));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With