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
Add optional reverse argument to sortBy
  • Loading branch information
Ludovico Fischer committed Jan 6, 2013
commit 98275fed0052a25cf85a68c09f4f995a2a9db65b
5 changes: 5 additions & 0 deletions test/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,11 @@ $(document).ready(function() {
});

deepEqual(actual, collection, 'sortBy should be stable');

var otherPeople = [{name: 'Harry', age: 35}, {name: 'Sally', age: 25}];
var otherPeople = _.sortBy(otherPeople, function(person){ return person.age; }, true);
equal(_.pluck(otherPeople, 'name').join(', '), 'Harry, Sally', 'characters sorted by age in reverse');

});

test('groupBy', function() {
Expand Down
10 changes: 7 additions & 3 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@
};

// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, value, context) {
_.sortBy = function(obj, value, reverse, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
Expand All @@ -308,8 +308,12 @@
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;
if (a > b || a === void 0) {
return reverse ? -1 : 1;
}
if (a < b || b === void 0) {
return reverse ? 1 : -1;
}
}
return left.index < right.index ? -1 : 1;
}), 'value');
Expand Down