title: Backbone.js Performance - Adding a class to first and last model of a nested collection
body: <p>I have a list of ~100 products that are displayed in a long list on one page. Each product belongs to one category, I have about 5 categories. Every product has a category_id.</p>
  
  <p>I want to add a '.first' class to every first product of a category and a '.last' class to every last product of a category.</p>
  
  <p>Performance is key, I came up with a few solutions myself but the were very poorly written and too cumbersome.</p>
  
  <p>Example data:</p>
  
  <pre><code>products = {
     id: 1, category_id: 1;
     id: 2, category_id: 1;
     id: 3, category_id: 1;
     id: 4, category_id: 2;
     id: 5, category_id: 2;
     id: 6, category_id: 2;
     id: 7, category_id: 3;
     id: 8, category_id: 3;
     ...
  }
  </code></pre>
  
  <p>Result I'm looking for:</p>
  
  <pre><code>&lt;ul&gt;
  
    &lt;li class='first' id='1'&gt;&lt;/li&gt;
    &lt;li id='2'&gt;&lt;/li&gt;
    &lt;li class='last' id='3'&gt;&lt;/li&gt;
  
    &lt;li class='first' id='4'&gt;&lt;/li&gt;
    &lt;li id='5'&gt;&lt;/li&gt;
    &lt;li class='last' id='6'&gt;&lt;/li&gt;
  
    &lt;li class='first' id='7'&gt;&lt;/li&gt;
    &lt;li id='8'&gt;&lt;/li&gt;
    ...
  &lt;/ul&gt;
  </code></pre>
  
  <p>EDIT: Thank you for the help @niemand! I used groupBy and this is what I have so far. Is this a good way to go about this, performance wise?</p>
  
  <pre><code>window.firsts = []
  window.lasts = []
  @grouped = _.groupBy(@collection.toJSON(), 'category_id')
  _.each @grouped, (group) -&gt;
    window.firsts.push new App.Models.Piece(_.first(group)).get('id')
    window.lasts.push new App.Models.Piece(_.last(group)).get('id')
  </code></pre>
  
  <p>This way I can check if window.firsts or window.lasts contains the current model's id when I am rendering out each model view and apply the correct class. If there is a more performant way of going about this I'd love to know!</p>