Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using underscore.js groupBy with Ember.js

Is it possible to use underscore's groupBy function with ember.js?

I have the following attempt which is obviously not working:

var activities = App.store.findMany(App.Activity, feed.mapProperty('id').uniq()) 
var grouped = _.groupBy(activities, function(activity){
  return activity.get('dateLabel;')
});

I get the following error:

Object App.Activity has no method 'get'

The store is loaded with the correct data so findMany will not make a remote call.

The problem is that findMany returns a DS.ManyArray which is probably a lot different than what _.groupBy is looking for.

like image 593
dagda1 Avatar asked Jun 05 '12 14:06

dagda1


1 Answers

You could implement your own groupBy function tailored for ember-data DS-ManyArray objects and extend _ with it:

_.emberArrayGroupBy = function(emberArray, val) {
  var result = {}, key, value, i, l = emberArray.get('length'),
      iterator = _.isFunction(val) ? val : function(obj) { return obj.get(val); };

  for (i = 0; i < l; i++) {
    value = emberArray.objectAt(i);
    key   = iterator(value, i);
    (result[key] || (result[key] = [])).push(value);
  }
  return result;
};

Now you can call

var grouped = _.emberArrayGroupBy(activities, function(activity) {
  return activity.get('dateLabel');
});

or more simply

var grouped = _.emberArrayGroupBy(activities, 'dateLabel');

The function above is based on underscore's original groupBy() implementation, which looks very similar:

_.groupBy = function(obj, val) {
  var result = {};
  var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
  each(obj, function(value, index) {
    var key = iterator(value, index);
    (result[key] || (result[key] = [])).push(value);
  });
  return result;
};
like image 53
Tomalak Avatar answered Oct 19 '22 23:10

Tomalak