A best implementation of sortBy
method by implementing Schwartzian transform can be found here: gist: sortBy.js
For now we are going to try this approach gist: sortBy-old.js.
Let's create a method to sort arrays being able to arrange objects by some property.
Creating the sorting function
var sortBy = (function () {
//cached privated objects
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((x !== null && typeof x === "object" && x[this.prop]) || x);
};
// Creates a method for sorting the Array
// @array: the Array of elements
// @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
return function (array, o) {
if (!(array instanceof Array) || !array.length)
return [];
if (_toString.call(o) !== "[object Object]")
o = {};
if (typeof o.parser !== "function")
o.parser = _parser;
o.desc = !!o.desc ? -1 : 1;
return array.sort(function (a, b) {
a = _getItem.call(o, a);
b = _getItem.call(o, b);
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
sortBy(data, { 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
sortBy(data, {
prop: "date",
desc: true,
parser: function (item) {
//ignore case sensitive
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
sortBy(data, {
prop: "date",
parser: function (item) {
return new Date(item);
}
});
Here you can play with the above example:
http://jsbin.com/kucawudaco/