Reputation: 12669
function MyController($scope) {
var singleSort = [
{ "text": "Second", "a": 2 },
{ "text": "Fifth", "a": 5 },
{ "text": "First", "a": 1 },
{ "text": "Fourth", "a": 4 },
{ "text": "Third", "a": 3 }
];
var multipleSort = [
{ "text": "Second", "a": 1, "b": 2 },
{ "text": "Fifth", "a": 2, "b": 2 },
{ "text": "First", "a": 1, "b": 1 },
{ "text": "Fourth", "a": 2, "b": 1 },
{ "text": "Third", "a": 1, "b": 3 }
];
var singleSortIterator = function(item) {
return item.a;
};
var multipleSortIterator = function(item) {
return [item.a, item.b];
};
var singleSortReversedIterator = function(item) {
return -item.a;
};
var multipleSortReversedIterator = function(item) {
return -[item.a, item.b];
};
$scope.singleSort = _.sortBy(singleSort, singleSortIterator);
$scope.multipleSort = _.sortBy(multipleSort, multipleSortIterator);
$scope.singleSortReversed = _.sortBy(singleSort, singleSortReversedIterator);
$scope.multipleSortReversed = _.sortBy(multipleSort, multipleSortReversedIterator);
}
The sorting algorithms are all working apart from the multipleSortReversed. Is there anything obvious wrong here?
http://jsfiddle.net/andybooth/QEBUx/
Results I'm getting are
Single sort
First
Second
Third
Fourth
Fifth
Multiple sort
First
Second
Third
Fourth
Fifth
Single sort (reversed)
Fifth
Fourth
Third
Second
First
Multiple sort (reversed)
Second
Fifth
First
Fourth
Third
Upvotes: 0
Views: 141
Reputation: 23664
I don't think uderscore can sort by multiple properties but I've implemented multi sort using plain javascript sort function
var helper = function(x,y) {
var r = 0;
if(x.a > y.a) {r+=10;}
if(x.a < y.a) {r-=10;}
if(x.b > y.b) {r+=1;}
if(x.b < y.b) {r-=1;}
return r;
}
var asc = [{a:2,b:1},{a:1,b:2},{a:1,b:1},{a:2,b:2}].sort(function(x,y) {
return helper(x,y);
});
var desc = [{a:2,b:1},{a:1,b:2},{a:1,b:1},{a:2,b:2}].sort(function(x,y) {
return -1 * helper(x,y);
});
The main idea is in helper. You need to make sure the values that get returned are in the correct order based on the property priority sorting. possible values: 11,10,1,0,-1,-10,-11.
Upvotes: 2
Reputation: 388
Using http://linqjs.codeplex.com seems to work well for multiple ordering http://jsfiddle.net/andybooth/caQjf/.
$scope.singleSortReversed = Enumerable.From(singleSort).OrderByDescending(orderByA).ToArray();
$scope.multipleSortReversed = Enumerable.From(multipleSort).OrderByDescending(orderByA).ThenByDescending(orderByB).ToArray();
However, a solution using underscorejs would still be useful. I believe the suggested [-item.a, -item.b] from @cuzzae still returns the items in the wrong order, not reversed, as required.
Upvotes: 1
Reputation: 1535
What I can see at a glance is
var multipleSortReversedIterator = function(item) {
return -[item.a, item.b]; // will return NaN
// change to return [-item.a, -item.b];
};
Upvotes: 1