Underscore.js.filter () and .any ()

I have an array of objects eventcalled events. Each eventhas an marketsarray containing objects market. Inside there is another array with a name outcomescontaining outcomeobjects.

In this question , I asked the [Underscore.js] method to find all events that have markets that have results that have a property with a name test. The answer was:

// filter where condition is true
_.filter(events, function(evt) {

    // return true where condition is true for any market
    return _.any(evt.markets, function(mkt) {

        // return true where any outcome has a "test" property defined
        return _.any(mkt.outcomes, function(outc) {
            return outc.test !== "undefined" && outc.test !== "bar";
        });
    });
});

This works fine, but I wonder how I would change it if I wanted to filter out the results for each market, so that I would market.outcomesonly keep the results that were equal bar. Currently, it only gives me markets that have results that have some properties set test. I want to cut out those that don't.

+5
source share
1 answer

Make a simple loop using the splice method to remove the array:

var events = [{markets:[{outcomes:[{test:x},...]},...]},...];
for (var i=0; i<events.length; i++) {
    var mrks = events[i].markets;
    for (var j=0; j<mrks.length; j++) {
        var otcs = mrks[j].outcomes;
        for (var k=0; k<otcs.length; k++) {
            if (! ("test" in otcs[k]))
                 otcs.splice(k--, 1); // remove the outcome from the array
        }
        if (otcs.length == 0)
            mrks.splice(j--, 1); // remove the market from the array
    }
    if (mrks.length == 0)
        events.splice(i--, 1); // remove the event from the array
}

This code will remove all results that do not have a property test, all empty markets, and all empty events from the array events.

The Underscore version might look like this:

events = _.filter(events, function(evt) {
    evt.markets = _.filter(evt.markets, function(mkt) {
        mkt.outcomes = _.filter(mkt.outcomes, function(otc) {
            return "test" in otc;
        });
        return mkt.outcomes.length > 0;
    });
    return evt.markets.length > 0;
});
+5
source

All Articles