Search code examples
javascriptbackbone.jsfilter

Filter Backbone collection on multiple model attributes


I have a bit of a problem with how to best filter a Backbone collection on its models Attributes. My setup is like this:

I have a collection with several models in it. Each model has an attribute which holds an array of numbers ("type"). Like this:

- Collection
- model
    - id: 1
    - name
    - phone
    - type [3]
- model
    - id: 2
    - name
    - phone
    - type [2]
- model
    - id: 3
    - name
    - phone
    - type [1,2]

What I want to do here is to be able to filter this collections on the models "type" attribute.

I have this "type" attribute because this is for a contact list and each contact can be of several types. E.g. the collection should be able to be filtered on unlimited types. You should be able to filter on lets say type "1" and type "2" which will then show model 2 and model 3. Cause model 1 does not have the "type" 1.

Any good code examples or other help on this would be great. Thanks!


Solution

  • Hi here is code which can filter for multiple types, stored in array

    var typesTofilter=[5,1,2];//array of type tobe search.
        var f2=friends.filter(function(o){ var accept=false;                                    
                                           $(typesTofilter).each(function(i,val){
                                             if(_.indexOf(o.get('type'), val) >-1){
                                               accept= true;                      
                                                }
                                            })
                                            return accept; 
                             });
    

    And here is jsFiddle.