Barrie Reader
Barrie Reader

Reputation: 10713

Retrieve an object from an array with a specific parameter

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");

Upvotes: 1

Views: 40

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074485

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.

Upvotes: 4

Related Questions