# 如何使用underscore.js进行升序和降序排序？

2020/10/24 19:01 · javascript ·  · 0评论

``````_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
``````

``````var array = _.sortBy([2, 3, 1], function(num) {
return num;
});

console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
``````

``````_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
``````
``````// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]

// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
``````

``````//Ascending Order:
_.sortBy([2, 3, 1], function(num){
return num;
}); // [1, 2, 3]

//Descending Order:
_.sortBy([2, 3, 1], function(num){
return num * -1;
}); // [3, 2, 1]
``````

``````//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){
return s.charCodeAt() * -1;
});
``````

``````var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();
``````

``````var sortedDescAndFiltered = _.chain(collection)
.sortBy('propertyName')
.reverse()
.filter(_.property('isGood'))
.value();
``````

``````_.orderBy('collection', 'propertyName', 'desc')
``````

Mixin.js

``````_.mixin({
sortByOrder: function(stooges, prop, order) {
if (String(order) === "desc") {
return _.sortBy(stooges, prop).reverse();
} else if (String(order) === "asc") {
return _.sortBy(stooges, prop);
} else {
return stooges;
}
}
})
``````

``````var sort_order = "asc";
var stooges = [
{name: 'moe', age: 40},
{name: 'larry', age: 50},
{name: 'curly', age: 60},
{name: 'July', age: 35},
{name: 'mel', age: 38}
];

_.mixin({
sortByOrder: function(stooges, prop, order) {
if (String(order) === "desc") {
return _.sortBy(stooges, prop).reverse();
} else if (String(order) === "asc") {
return _.sortBy(stooges, prop);
} else {
return stooges;
}
}
})

// find elements
var banner = \$("#banner-message");
var sort_name_btn = \$("button.sort-name");
var sort_age_btn = \$("button.sort-age");

function showSortedResults(results, sort_order, prop) {
banner.empty();
banner.append("<p>Sorting: " + prop + ', ' + sort_order + "</p><hr>")
_.each(results, function(r) {
banner.append('<li>' + r.name + ' is '+ r.age + ' years old.</li>');
})
}

// handle click and add class
sort_name_btn.on("click", function() {
sort_order = (sort_order === "asc") ? "desc" : "asc";
var sortedResults = _.sortByOrder(stooges, 'name', sort_order);
showSortedResults(sortedResults, sort_order, 'name');
})

sort_age_btn.on('click', function() {
sort_order = (sort_order === "asc") ? "desc" : "asc";
var sortedResults = _.sortByOrder(stooges, 'age', sort_order);
showSortedResults(sortedResults, sort_order, 'age');
})
``````