AnApprentice
AnApprentice

Reputation: 111020

How to get a count of a items within a collection that match a specific criteria?

I have a collection like so:

{ "items": [
    {
     "id": "123",
     "meta": {
        "activity": 2
     }
    },
    {
     "id": "13423",
     "meta": {
        "activity": 4
     }
    }
]}

Given the collection, how can I get the collection's total activity? In the case above the result would be 6.

I'm using backbone and underscore.

Upvotes: 1

Views: 96

Answers (2)

cleaver
cleaver

Reputation: 370

You're using underscore.js, so you have some good tools at your disposal. Look at _.map() to get started.

var flatArray = _.map(collection.items, function(x){return x.meta.activity;});
// should return: [2,4]

Then you can use _.reduce() to turn this into a single value.

var total = _.reduce(flatArray, function(memo, num) {return memo + num;}, 0);
// should return: 6

There's lots of other great tools in underscore.js, it's worth a look to see if anything else would work for you too.

Upvotes: 1

Ma3x
Ma3x

Reputation: 6579

In underscore you can use the reduce function which will reduce a list of values into a single value using the given iterator function.

var myCollection = { "items": [
    {
        "id": "123",
        "meta": {
            "activity": 2
        }
    },
    {
        "id": "13423",
        "meta": {
            "activity": 4
        }
    }
]};

var totalActivity = _.reduce(myCollection.items, function(memo, item){ return memo + item.meta.activity; }, 0);

Upvotes: 1

Related Questions