Q:

Backbone Collection - Constructor

I am passing an array to new collection. Is it possible to filter the array by passing second parameter and check on the attr of the object in the array and create collection only if it pass the filter test.
collection = new Backbone.Collection([{name:'xy',age:24},{name:'y',age:35}])

Can I create a collection only for the object less than 30 years.

A:

You can use _.filter on your array before passing into the collection
collection = new Backbone.Collection(
     _.filter([{name:'xy',age:24},{name:'y',age:35}], 
              function(item) { return item.age < 30; }));

Or you can move your custom filtering logic into your collection initialize where you will get the models array what you can modify/filter
var Under30 = Backbone.Collection.extend({
    initialize: function(models, options) {
        for(var i = models.length - 1; i > 0; i-- ){
            if (models[i].age > 30){
                models.splice(i,1);
            }
        }
    }
});

var collection = new Under30([{name:'xy',age:24}, {name:'y',age:35}]);
console.log(collection.models.length); // will be 1

Demo JSFiddle.
You can extend this with supplying the filter predicate in the options parameter
var FilteredCollection = Backbone.Collection.extend({
        initialize: function(models, options) {
            for(var i = models.length - 1; i > 0; i-- ){
                if (options.filter && options.filter(models[i])){
                    models.splice(i,1);
                }
            }
        }
    });

And use it with
var collection = new FilteredCollection(
      [{name:'xy',age:24}, {name:'y',age:35}], 
      {
          filter: function(item) { 
              return item.age > 30; 
          }
      }
);
console.log(collection.models.length); // will be 1

