Get random element from associative array in javascript?

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

foo[songID] = songURL;

I am trying to create a shuffle. I would like to randomly select a song from this list. Is there an easy way to do this - the array is not indexed.

+5
source share
5 answers

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

You also have two different but related questions.

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

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

, . shuffle - ( , Fischer-Yates) .

var objectKeysShuffled = function (object) {
    return shuffle(Object.keys(object));
};
+5

, .

this.bgm = {} //I later added audio elements to this
this.playRandomBGM = function()
{
    var keys = Object.keys(this.bgm);
    self.currentBGM = keys[Math.floor(keys.length * Math.random())];
    console.log("Playing random BGM: " + self.currentBGM);
    self.bgm[self.currentBGM].play();
}
+2

- :

var obj = {
    'song1': 'http://...1',
    'song2': 'http://...2',
    'song3': 'http://...3',
    'song4': 'http://...4',
    'song5': 'http://...5',
    'song6': 'http://...6',
}, tempArr = [], len, rand, song;

for ( var key in obj )
    if ( obj.hasOwnProperty(key) )
        tempArr.push( obj[key] );

len = tempArr.length;
rand = Math.floor( Math.random() * len );
song = tempArr[rand];
document.write(song);

, , , , :

var songs = [
    {title: 'Song1', url: 'http://...1.mp3'},
    {title: 'Song2', url: 'http://...2.mp3'},
    {title: 'Song3', url: 'http://...3.mp3'}
];
0
function fetchRandom(arr) {
    var ret,
        i = 0;
    for (var key in arr){
        if (Math.random() < 1/++i){
           ret = key;
        }
    }
    return ret;
}

var randomSong = foo[fetchRandom(foo)];

. , .

0

:

function randomProperty(obj) {
  var a = [];
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      a.push(p);
    }
  }
  return a.length? obj[ a[a.length * Math.random() | 0]] : void 0;
}

, , .

0

All Articles