1

JSON:

[
   { score: 0.648 },
   { score: 0.945 }
]

Javascript:

_.sortBy(array, function(obj){ return obj.score });

However this returns just a copy of the original array. Nothing has changed. I want to sort the array by score in a descending way. Any ideas how to do that?

1 Answer 1

2

If you want to sort in descending order, complement the score:

_.sortBy(array, function(obj) { return -obj.score; });

For array sorting in general, outside of the world of Underscore, you can use the native .sort() on the JavaScript Array prototype. It takes two actual elements of the array as parameters, and should return a number less than, equal to, or greater than zero depending on the ordering relationship between the two elements.

In your case, that'd look like:

array.sort(function(o1, o2) {
  return -(o1.score - o2.score); // or just return o2.score - o1.score if you like
}

This scheme is far more flexible, because the sort mechanism gives you complete control and makes no assumptions (other than that your comparison function is consistent; if it's not, you get weird behavior).

Sign up to request clarification or add additional context in comments.

5 Comments

The Underscore sorting scheme is, in my not-worth-much opinion, a really bad mistake. It's at best a huge mess to sort a list of strings in reverse alphabetical order, for example.
great, looking forward to it
Note that sortBy has the advantage of only calling your custom function once per element of the array, rather than once per comparison between any two elements. That's not a problem with only two elements (it's actually better in that case!), but for large arrays or complex comparison functions, it's something to keep in mind.
@MarkReed: Right, the built in Schwartzian Transform is the big advantage of sortBy. sortBy is cumbersome for reversed string sorting though, there's no sane way to negate a string.
@MarkReed yes, that's true. In such cases it pays to transform the array in a linear pass into an array with substantially precomputed keys and index values. That way the sort can be cheaper, and it's just another linear pass to construct the full sorted array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.