How to sort descending an array with underscore
Avoid to sort manually. Let’s see how to sort descending an array with Underscore. And it’s very easy to change it to sort ascending.
Yes, I know underscoreJS provides the method sortBy but it sorts ascending, it returns an orderer array and there is not any parameter to sort descending.
Maybe you already have the answer.
Since we get the ascending orderer array, let’s just use array.reverse()!
Sort descending an array with underscore
So first, we’ll sort ascending the array and then will reverse the array in order to get it descending
var myArray = [
{ name: 'David', total: 6 },
{ name: 'John', total: 2 },
{ name: 'Joe', total: 8 },
{ name: 'Ana', total: 4 }
];
// First sort ASC
var ascending = _.sortBy(myArray, 'total');
// Then get DESC
var descending = ascending.reverse();
// Result:
[
{ name: 'Joe', total: 8 },
{ name: 'David', total: 6 },
{ name: 'Ana', total: 4 },
{ name: 'John', total: 2 }
]
Of course, you can do it in just one line
// That's it!
var descending = _.sortBy(myArray, 'total').reverse();
Probably very obvious but you know, sometimes we spend time in this details.