Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  16] [ 6]  / answers: 1 / hits: 54471  / 13 Years ago, mon, january 2, 2012, 12:00:00

I'm using Javascript sort (with Underscore.js):



_.sortBy([Bob, Mary, Alice], function (name) {return name})
> [Alice, Bob, Mary]


I would like the array to return the other way. How do I do that?




[Mary, Bob, Alice]




I don't want to reverse it after it's sorted - I want it to be created the other way around the first time.



Thanks.


More From » sorting

 Answers
78

I would just do what Underscore does under the hood: use the Array#sort method.



[Bob, Mary, Alice].sort(function (a, b) {
if (a < b) return 1;
if (b < a) return -1;
return 0;
});


Or if you don't want the original array modified, clone it first:



_.clone([Bob, Mary, Alice]).sort(...)

[#88269] Saturday, December 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reedmustafam

Total Points: 211
Total Questions: 83
Total Answers: 105

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;