1

I was wondering whether there is an easy way to select a random object from an array where one of the objects attributes matches a variable.

Something like this:

var ninjas = [
    { name: "Sanji Wu", affiliation: "good" },
    { name: "Chian Xi", affiliation: "good" },
    { name: "Chansi Xian", affiliation: "bad" },
    { name: "Chin Chu", affiliation: "bad" },
    { name: "Shinobi San", affiliation: "neutral" },
    { name: "Guisan Hui", affiliation: "neutral" }
];

function getRandom(attr) {
    var r = Math.floor(Math.random() * ninjas.length);

    //pseudo code below  
    if (this affiliation is "attr") {
        return a random one that matches
    }
    // end pseudo code
};

var randomItem = getRandom("good");

1 Answer 1

4

Fairly straight-forward to create an array with only the matching elements, then grab an entry at random from it:

function getRandom(desiredAffiliation) {
    var filtered = ninjas.filter(function(ninja) {
        return ninja.affiliation == desiredAffiliation;
    });
    var r = Math.floor(Math.random() * filtered.length);
    return filtered[r];
}

If you want to make the property you look for a runtime thing, you can do that too, using brackets notation:

function getRandom(propName, desiredValue) {
    var filtered = ninjas.filter(function(ninja) {
        return ninja[propName] == desiredValue;
    });
    var r = Math.floor(Math.random() * filtered.length);
    return filtered[r];
}

You'll probably want to tweak those to allow for the possibility there are no matching entries. Right now they'll return undefined in that case, since they'll try to return the 0th entry of an array with nothing in it, which isn't an error, but results in the value undefined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.