I am currently using underscorejs for sort my json sorting. Now I have asked to do an ascending
and descending
sorting using underscore.js. I do not see anything regarding the same in the documentation. How can I achieve this?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Descending order using underscore can be done by multiplying the return value by -1.
If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.
Similar to Underscore library there is another library called as 'lodash' that has one method "orderBy" which takes in the parameter to determine in which order to sort it. You can use it like
For some reason, it's not documented on the website docs.
You can use
.sortBy
, it will always return an ascending list:But you can use the .reverse method to get it descending:
Or when dealing with numbers add a negative sign to the return to descend the list:
Under the hood
.sortBy
uses the built in.sort([handler])
:The Array prototype's reverse method modifies the array and returns a reference to it, which means you can do this:
Also, the underscore documentation reads:
which means you can also use
.reverse()
while chaining:Underscore Mixins
Extending on @emil_lundberg's answer, you can also write a "mixin" if you're using Underscore to make a custom function for sorting if it's a kind of sorting you might repeat in an application somewhere.
For example, maybe you have a controller or view sorting results with sort order of "ASC" or "DESC", and you want to toggle between that sort, you could do something like this:
Mixin.js
Usage Example
Here's a JSFiddle demonstrating this: JSFiddle for SortBy Mixin