DarkLeafyGreen
DarkLeafyGreen

Reputation: 70406

Using underscores sortBy to sort objects

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?

Upvotes: 1

Views: 1288

Answers (1)

Pointy
Pointy

Reputation: 413702

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).

Upvotes: 2

Related Questions