Bemmu Bemmu - 3 months ago 13
Javascript Question

Pick random property from a Javascript object

Suppose you have a Javascript object like {'cat':'meow','dog':'woof' ...}
Is there a more concise way to pick a random property from the object than this long winded way I came up with:

function pickRandomProperty(obj) {
var prop, len = 0, randomPos, pos = 0;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
len += 1;
}
}
randomPos = Math.floor(Math.random() * len);
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (pos === randomPos) {
return prop;
}
pos += 1;
}
}
}

Answer

Picking a random element from a stream

function pickRandomProperty(obj) {
    var result;
    var count = 0;
    for (var prop in obj)
        if (Math.random() < 1/++count)
           result = prop;
    return result;
}
Comments