Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two collection in backbone

Tags:

backbone.js

How can i compare two collections in backbone?

I have two collection 1C contains 1,2,3 while 2C contains 2,4,5 What i want to do is to remove 2 from 2C because 1C already has a value of 2 after that normally render the collection.

I tried this

this.1C.each(function(model1){
  this.2C.each(function(model2){
     if(model1 === model2){
        2C.remove(model2);
     }
  });
});

But it doesnt work. Any ideas?

like image 816
n0minal Avatar asked Mar 18 '26 07:03

n0minal


1 Answers

You have something called the Difference operator http://underscorejs.org/#difference. Which you can use like below

var x = _.difference([1,2,3,4],[1,2]); console.log(x); //gives [3,4]

In your case you probably should do this

var reducedCollection = _.difference(this.1C.toJSON(),this.2C.toJSON());

which now will provide expected result

like image 169
Deeptechtons Avatar answered Mar 21 '26 10:03

Deeptechtons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!