Quantcast
Channel: Appcelerator Developer Center Q&A Unanswered Questions 20
Viewing all articles
Browse latest Browse all 8068

How to sort a collection, particularly descending

$
0
0

I was going to ask this question, but I found an answer so I thought I should post it since I hadn't seen this in the Q&A.

Is this the most appropriate way to handle sorting a collection?

Sort in ASCENDING order of a numerical attribute

var foos = Alloy.Collections.foo;
 
foos.fetch();
 
// assuming my number attribute is "created_at"
foos.comparator = function(foo) {
  return foo.get('created_at');
};
Sort in DESCENDING order of a numerical attribute
var foos = Alloy.Collections.foo;
 
foos.fetch();
 
// assuming my number attribute is "created_at"
// note the "-" sign before retrieving the attribute
foos.comparator = function(foo) {
  return -foo.get('created_at');
};
Sort in DESCENDING order of a NON-numerical attribute
var foos = Alloy.Collections.foo;
 
foos.fetch();
 
function reverseSortBy(sortByFunction) {
  return function(left, right) {
    var l = sortByFunction(left);
    var r = sortByFunction(right);
 
    if (l === void 0) return -1;
    if (r === void 0) return 1;
 
    return l < r ? 1 : l > r ? -1 : 0;
  };
}
 
foos.comparator = function(foo) {
  return foo.get('name');
};
 
foos.comparator = reverseSortBy(foos.comparator);
Credit: Andrew Newdigate and others on SO

Viewing all articles
Browse latest Browse all 8068

Trending Articles