Underscore.js has a sortby function that supports arrays and objects sorted by one field:
The code is as follows |
Copy Code |
var ret = _.sortby ([5, 2, 3, 4, 1], function (num) { return num; }); >> [1, 2, 3, 4, 5] |
However, if you want to display in reverse order, Underscore.js still does not have the transparent support reverse operation. You can actually borrow the elements you want to sort by taking a negative
The code is as follows |
Copy Code |
var ret = _.sortby ([5, 2, 3, 4, 1], function (num) { Return-num; }); >> [5, 4, 3, 2, 1] |
This makes it very convenient to do reverse operation.
The strength of SortBy is in the ordering of one of the elements of an object, such as:
The code is as follows |
Copy Code |
var ret = _.sortby ([{ Name: "Tim", Index:2 }, { Name: "Qin", Index:1 }, { Name: "Crazy", Index:4 }, { Name: "It", Index:3 }], function (data) { Return-data.index; }); >> [{ Name: ' Crazy ', Index:4 }, { Name: ' The ', Index:3 }, { Name: ' Titus ', Index:2 }, { Name: ' Qin ', Index:1 }] |
Maybe my language ability is limited, say prototype.js sortby when I do not know how to express in words as well.
I have been so hard to read the interpretation code, I am sorry!