Maybe this approach can be useful:
We are going to create a method to sort the array that be able to arrange objects by a property.
Creating the sorting function
(function() {
var _toString = Object.prototype.toString,
//the default parser function
_parser = function (x) { return x; },
//gets the item to be sorted
_getItem = function (x) {
return this.parser((_toString.call(x) == "[object Object]" && x[this.prop]) || x);
};
// Creates a sort method in the Array prototype
Object.defineProperty(Array.prototype, "sortBy", {
configurable: false,
enumerable: false,
// @o.prop: property name (if it is an Array of objects)
// @o.desc: determines whether the sort is descending
// @o.parser: function to parse the items to expected type
value: function (o) {
if (_toString.call(o) != "[object Object]")
o = {};
if (_toString.call(o.parser) != "[object Function]")
o.parser = _parser;
//if @o.desc is false: set 1, else -1
o.desc = [1, -1][+!!o.desc];
return this.sort(function (a, b) {
a = _getItem.call(o, a);
b = _getItem.call(o, b);
return ((a > b) - (b > a)) * o.desc;
//return o.desc * (a < b ? -1 : +(a > b));
});
}
});
})();
Setting unsorted data
var data = [
{date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
{date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
{date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"},
{date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"}
];
Using it
Finally, we arrange the array, by "date"
property as string
//sort the object by a property (ascending)
//sorting takes into account uppercase and lowercase
data.sortBy({ prop: "date" });
If you want to ignore letter case, set the "parser"
callback:
//sort the object by a property (descending)
//sorting ignores uppercase and lowercase
data.sortBy({
prop: "date",
desc: true,
parser: function (item) {
return item.toUpperCase();
}
});
If you want to treat the "date" field as Date
type:
//sort the object by a property (ascending)
//sorting parses each item to Date type
data.sortBy({
prop: "date",
parser: function (item) {
return new Date(item);
}
});
Here you can play with the above example:
http://jsbin.com/pavina/5/edit?js,output