I\'m trying to achieve a \"group by\" functionality in Ember.js and its proving more difficult than I originally thought.
[{date: \'2014-01-15T16:22:16-08:00\',
Here is an implementation, made available on Array
objects:
var groupByMethod = Ember.Mixin.create({
groupBy: function(key) {
var result = [];
var object, value;
this.forEach(function(item) {
value = item.get ? item.get(key) : item[key];
object = result.findProperty('value', value);
if (!object) {
object = {
value: value,
items: []
};
result.push(object);
}
return object.items.push(item);
});
return result.getEach('items');
}
});
groupByMethod.apply(Array.prototype);
> var posts = [{id: 1, author: 'John'}, {id:2, author: 'Paul'}, {id:4, author: 'Paul'}, {id:5, authour: 'Tom'}];
> posts.groupBy('author')