From 6b8a99ba395c6b53fdec24c8d134861b47a09d65 Mon Sep 17 00:00:00 2001 From: "Yi, EungJun" Date: Sat, 31 Mar 2012 02:27:49 +0900 Subject: [PATCH] Adding the ability to _.sortBy(list, 'property') --- test/collections.js | 4 ++++ underscore.js | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/test/collections.js b/test/collections.js index 18b242769..68e90246f 100644 --- a/test/collections.js +++ b/test/collections.js @@ -235,6 +235,10 @@ $(document).ready(function() { var people = [{name : 'curly', age : 50}, {name : 'moe', age : 30}]; people = _.sortBy(people, function(person){ return person.age; }); equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'stooges sorted by age'); + + var list = ["one", "two", "three", "four", "five"]; + var sorted = _.sortBy(list, 'length'); + equal(sorted.join(' '), 'one two four five three', 'sorted by length'); }); test('collections: groupBy', function() { diff --git a/underscore.js b/underscore.js index 44226a07c..203b6d147 100644 --- a/underscore.js +++ b/underscore.js @@ -262,7 +262,8 @@ }; // Sort the object's values by a criterion produced by an iterator. - _.sortBy = function(obj, iterator, context) { + _.sortBy = function(obj, val, context) { + var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; return _.pluck(_.map(obj, function(value, index, list) { return { value : value,