javascript - A better way than chaining _.groupBy? -


when array stores data grouped month , day of date not year (i doing maximum, minimum, , average values each day there data for)

the problem array stores array of 2-3 values day , month within date key value. 2-3 indices each have array of length 1 holds reference object has actual data point (level) need. object contains 3 attributes, date, id (which null), , level float.

i either need find way 2-3 indices hold object directly, or find way _.each can access level.

any thoughts?

var groupeddata = _.groupby(data, "date");  var groupedlevels = _.groupby(groupeddata, function (points, date) {   var dateparsed = parsedate(date);   var month = dateparsed.getmonth();   var day = dateparsed.getdate();    var monthday = month + "-" + day;    return monthday; });  _.each(groupedlevels, function (points, date) {   var levels = _.map(_.pluck(points, "level"), parsefloat);    minimum.push([ date, r.min(levels) ]);   maximum.push([ date, r.max(levels);    var averagelevel = r.sum(levels) / levels.length;    average.push([date, averagelevel]); }) 

so data, is, original input looks (a sample piece):

[ { date: "2009-01-01",     id: null,     level: "0.08",   },   // ... ] 

currently, groupeddata this:

{ "2009-01-01":   [ { date: "2009-01-01",       id: null,       level: "0.08"     }   ],   // ... } 

groupedlevels looks this, example:

{ "0-1":   [ [ { date: "2009-01-01".         id: null,         level: "0.08"       }     ],     // ...   ],   // ... } 

i want skip having arrays of length 1 , have object stored there.

i think can fix immediate issue replacing line:

var levels = _.map(_.pluck(points, "level"), parsefloat); 

with this:

var levels = _.map(_.pluck(points[0], "level"), parsefloat); 

...but think real problem might you're doing groupby twice when don't need to. single groupby ought equivalent, without nested array:

var groupedlevels = _.groupby(data, function(item) {   var dateparsed = parsedate(item.date);   var month = dateparsed.getmonth();   var day = dateparsed.getdate();   return month + '-' + day; }); 

with this, each should work expected.


Comments