Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions test/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,10 @@

list = ['q', 'w', 'e', 'r', 't', 'y'];
deepEqual(_.sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses _.identity if iterator is not specified');

var people2 = [{name : 'curly', age : 50},{name: 'moe', age: 30},{name : 'curly', age : 27}];
people2 = _.sortBy(people2, ['name',function(p){return p.age;}] );
deepEqual(_.pluck(people2, 'age'), [27,50,30], 'stooges sorted first by name, then age');
});

test('groupBy', function() {
Expand Down
23 changes: 15 additions & 8 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -334,21 +334,28 @@
return _.shuffle(obj).slice(0, Math.max(0, n));
};

// Sort the object's values by a criterion produced by an iteratee.
// Sort the object's values by a criterion produced by one or more iteratees.
_.sortBy = function(obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context);
var iteratees = [].concat(iteratee).map(function(i){
return _.iteratee(i,context);
});
var length = iteratees.length;
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
criterias: _.map(iteratees,function(it){
return it(value,index,list);
})
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
for (var n = 0; n < length; n++) {
var a = left.criterias[n];
var b = right.criterias[n];
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
}
return left.index - right.index;
}), 'value');
Expand Down