backbone.js - How to filter collection based on another collection using underscore.js -


i have collection called `mainitems``

this.mainitems; 

which contains 18 models. , 1 more collection object contains selected items:

this.seleteditems; 

i need filter main collection object based on other collection.

i have tried below approach:

    var = this;     var model = _.reject(that.filtereditems.models, function(model1){         return _.filter(that.collection.models, function(model2) {            return model1.id == model2.id;         });     }); 

but approach not working properly. possible filter main items avoiding second iteration ?

please help!

you can use underscore's methods proxied backbone simplify filter.

for example, list models in mainitems without models in selecteditems, use

// reject models found in selecteditems var filtered = mainitems.reject(function(m) {     return selecteditems.get(m.id); }); 

note collection.get hash lookup, making backbone equivalent the answer pointed @gruffbunny in comments.

and demo

var mainitems = new backbone.collection([      {id: 1},      {id: 2},      {id: 3},      {id: 4}  ]);    var selecteditems = new backbone.collection([      {id: 2}  ]);    var keep = mainitems.reject(function(m) {      return selecteditems.get(m.id);  });    console.log(_.pluck(keep, 'id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -