我推荐
GitHub: Array sortBy - 这是一个最好的
sortBy
方法实现,它使用
Schwartzian transform。
但是现在我们将尝试这种方法
Gist: sortBy-old.js。
让我们创建一个函数来对数组进行排序,能够按某个属性排序对象。
创建排序函数
var sortBy = (function () {
var toString = Object.prototype.toString,
parse = function (x) { return x; },
getItem = function (x) {
var isObject = x != null && typeof x === "object";
var isProp = isObject && this.prop in x;
return this.parser(isProp ? x[this.prop] : x);
};
return function sortby (array, cfg) {
if (!(array instanceof Array && array.length)) return [];
if (toString.call(cfg) !== "[object Object]") cfg = {};
if (typeof cfg.parser !== "function") cfg.parser = parse;
cfg.desc = !!cfg.desc ? -1 : 1;
return array.sort(function (a, b) {
a = getItem.call(cfg, a);
b = getItem.call(cfg, b);
return cfg.desc * (a < b ? -1 : +(a > b));
});
};
}());
设置未排序数据
var data = [
{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:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
{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-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
{date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"},
{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-01T16:17:54Z", 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"}
];
使用它
将数组按 "date"
作为 String
排列
sortBy(data, { prop: "date" });
如果您想忽略大小写,可以设置parser
回调函数:
sortBy(data, {
prop: "type",
parser: (t) => t.toUpperCase()
});
如果您想将
"date"
字段转换为
Date
类型:
sortBy(data, {
prop: "date",
desc: true,
parser: (d) => new Date(d)
});
在这里,您可以与代码进行互动:jsbin.com/lesebi
感谢@Ozesh的反馈,已修复与具有falsy值属性相关的问题。