Search code examples
backbone.jsunderscore.js

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.


Solution

  • 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.