Ember.Enumerable no group by?


#1

A few things, first off, why is there no groupBy in Ember.Enumerable ? Is there some other way of doing it with the build in functions that I’m not aware of, or am I supposed to do it somewhere other than my controller?

I’m still very new to ember so I may have missed something. But I have some data I’d like to group and sort by date (and in the groupings, by start time) and I can’t figure out how to do this with ember.

Thanks!


#2

I was looking for one the other day and just ended up doing this. In this case I am grouping by the type property and it’s content is pushed to the contents array. It’s not very optimal, but it works in my use-case. I stuck this on my array controller but it can be applied to anything really.

groupedResults: function () {
   var result = [];

   this.get('content').forEach(function(item) {
      var hasType = result.findBy('type', item.get('type');

      if(!hasType) {
         result.pushObject(Ember.Object.create({
            type: item.get('type'),
            contents: []
         }));
      }

      result.findBy('type', item.get('type')).get('contents').pushObject(item);
   });

   return result;
}.property('content.[]')

#3

Nice! That looks awesome. So in your template, you could do something like this to loop through them and display it grouped?

{#each groupedResults}
  <h1>{{type}}</h1>
  {{#each contents}}
     <!-- assuming it has a name -->
     {{name}}
  {{/each}}
{{/each}}

#4

Yup, that’s exactly what I am doing.


#5

Hey fellas, I turned your code into a computed property


#6

Awesome, thanks! I’m going to put this into my EAK project :smile:


#7

You’re welcome and thank you for giving me material for next week’s Ember Sherpa tweets :slight_smile:


#9

Love it, something along the lines of this should find its way into Ember.


#10

Agreed! A groupBy function like this, as well as a sortBy with the same usage would be awesome. It’s definitely something I would use and was surprised to find that this doesn’t exist in ember already


#11

sortBy is available in Ember as of version 1.2, but I think groupByis still missing. And I agree that there should be an implementaion in Ember core.