Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a Backbone.js collection by index

I have Backbone.js collection that holds (for example) 30 items.

I want to pass to my template filtered collection consist of every 3rd item in the original collection.

Does anyone know how it can be done elegantly? CoffeeScript code is preferred.

like image 518
liorix Avatar asked Feb 22 '23 01:02

liorix


1 Answers

Assuming here that originalCollection is your existing collection

var newCollection = new Backbone.Collection();

for (var i = 0, l = originalCollection.length; i < l; i++) {
  if (i % 3 === 0) { newCollection.add(originalCollection.models[i]); }
}

This code works by looping through each existing model, and only adding the model the new collection if it's index is a multiple of 3.

You could make this a little nicer, by using the underscore each method exposed by Underscore.js in Backbone Collections:

var newCollection = new Backbone.Collection();

originalCollection.each(function (model, index) {
  if (index % 3 === 0) { newCollection.add(model); }
});

Converting the above to CoffeeScript results in:

newCollection = new Backbone.Collection()
originalCollection.each (model, index) ->
  newCollection.add model  if index % 3 is 0
like image 53
isNaN1247 Avatar answered Feb 27 '23 08:02

isNaN1247