Try this:
var output = _.chain(d).groupBy("season").map(function (group) {
return _.chain(group).sortBy("price").first().value();
}).value();
See the demo: http://jsfiddle.net/Ns2MJ/
Pregunta
Any suggestion on how to do grupby + sortby together using UnderscoreJS?
Having following collection, I would like to find smallest price per season:
var d = [{
"price": 27.25,
"season": 2
},
{
"price": 10,
"season": 3
},
{
"price": 21,
"season": 2
}];
I was able to group using the below:
_.chain(d).groupBy('season').map(function(value, key) {
return {
season: key,
obj: value
}
}).value();
which gets me:
[
{"season":"2","obj":[{"price":27.25,"season":2},{"price":21,"season":2}]},
{"season":"3","obj":[{"price":10,"season":3}]}
]
Solución
Try this:
var output = _.chain(d).groupBy("season").map(function (group) {
return _.chain(group).sortBy("price").first().value();
}).value();
See the demo: http://jsfiddle.net/Ns2MJ/
Otros consejos
Get the minimum price of each season in your map
function:
_.chain(d).groupBy('season').map(function(value, key) {
return {
season: key,
price: _.chain(value).pluck('price').min().value()
}
}).sortBy('price').value();
You can use _min
combined with _.property
to extract the smallest price in a group:
var output = _.chain(d).groupBy('season').map(function (group) {
return _.min(group, _.property('price'));
}).value();
And a demo http://jsfiddle.net/nikoshr/Edf5g/