Skip to content

Instantly share code, notes, and snippets.

@spoike
Last active December 19, 2015 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spoike/5876227 to your computer and use it in GitHub Desktop.
Save spoike/5876227 to your computer and use it in GitHub Desktop.
Ranked lists in lodash
// Use _.mixin to extend lodash
_.mixin({
'rankedBy': function(c, rank_cb, reversed) {
var ranks = [], pos = 0, _ = this;
var grouped = _.groupBy(c, rank_cb);
ranks = _.sortBy(grouped, function(v) {
return rank_cb(v[0]);
});
if (reversed) {
ranks = (ranks.reverse());
}
return ranks;
}
});
// Test
var myarr = [
{
"name": "Anna",
"score": 123
},
{
"name": "Borat",
"score": 456
},
{
"name": "Cecil",
"score": 321
},
{
"name": "George",
"score": 456
}
];
var score_cb = function(p) { return p.score; };
var print = function(ranked) {
_.each(ranked, function(rank, idx) {
var names = _.map(rank, function(v){ return v.name; });
console.log((1+idx)+'.' , '(' + rank[0].score + ')' , names.join(', '));
});
};
console.log('Testrun');
print(_.rankedBy(myarr, score_cb));
console.log('Testrun wrapped');
print(_(myarr).rankedBy(score_cb));
console.log('Reversed');
print(_.rankedBy(myarr, score_cb, true));
@spoike
Copy link
Author

spoike commented Jun 27, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment