diff --git a/test/collections.js b/test/collections.js index 6e000993d..6ebd51251 100644 --- a/test/collections.js +++ b/test/collections.js @@ -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() { diff --git a/underscore.js b/underscore.js index 1105f6012..69011a52d 100644 --- a/underscore.js +++ b/underscore.js @@ -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 { @@ -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');