Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnderscoreJS: groupby + sortby

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}]}
] 
like image 673
Iladarsda Avatar asked Dec 16 '25 15:12

Iladarsda


2 Answers

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/

like image 184
Aadit M Shah Avatar answered Dec 19 '25 06:12

Aadit M Shah


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();
like image 30
Bergi Avatar answered Dec 19 '25 05:12

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!