Ember.Enumerable no group by?

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!

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.[]')
5 Likes

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}}

Yup, that’s exactly what I am doing.

Hey fellas, I turned your code into a computed property

6 Likes

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

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

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

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

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.

  1. Still no groupBy in Ember :cry:

But that is not a thing Ember needs. Just npm install lodash and import groupBy from 'lodash/groupBy'.

We’ve worked hard to stop needing custom everything, now that the JS ecosystem has caught up enough to provide these things.