Last active
December 19, 2015 01:28
-
-
Save spoike/5876227 to your computer and use it in GitHub Desktop.
Ranked lists in lodash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test available at http://jsfiddle.net/spoike/hUJeF/