Search code examples
javascriptbackbone.js

Backbone count number of models in a collection that have attributes


I am trying to get the number of models that appear in a collection where the attribute value appears in an array, for example I have an array,

var array = [1, 2, 3, 4, 5]

I wanting to get the number of models from a collection that have an attribute called status that is equal to one those values in the array is this possible?


Solution

  • You could filter out all the models which has a status contained in the array, and then take the length of this resulting array:

    var numOfModels = collection.filter(function(model) { 
      return array.indexOf(model.get('status')) !== -1;
    }).length;