Recomiendo GitHub: Array sortBy : una mejor implementación del sortBy
método que utiliza la transformación Schwartzian
Pero por ahora vamos a probar este enfoque Gist: sortBy-old.js .
Creemos un método para ordenar las matrices pudiendo organizar los objetos por alguna propiedad.
Crear la función de clasificación
var sortBy = (function () {
var toString = Object.prototype.toString,
// default parser function
parse = function (x) { return x; },
// gets the item to be sorted
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);
};
/**
* Sorts an array of elements.
*
* @param {Array} array: the collection to sort
* @param {Object} cfg: the configuration options
* @property {String} cfg.prop: property name (if it is an Array of objects)
* @property {Boolean} cfg.desc: determines whether the sort is descending
* @property {Function} cfg.parser: function to parse the items to expected type
* @return {Array}
*/
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));
});
};
}());
Establecer datos sin clasificar
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"}
];
Usándolo
Organizar la matriz, "date"
comoString
// sort by @date (ascending)
sortBy(data, { prop: "date" });
// expected: first element
// { date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab" }
// expected: last element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"}
Si desea ignorar mayúsculas y minúsculas, configure la parser
devolución de llamada:
// sort by @type (ascending) IGNORING case-sensitive
sortBy(data, {
prop: "type",
parser: (t) => t.toUpperCase()
});
// expected: first element
// { date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "Cash" }
// expected: last element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa" }
Si desea convertir el "date"
campo como Date
tipo:
// sort by @date (descending) AS Date object
sortBy(data, {
prop: "date",
desc: true,
parser: (d) => new Date(d)
});
// expected: first element
// { date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "Visa"}
// expected: last element
// { date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab" }
Aquí puedes jugar con el código:
jsbin.com/lesebi
Gracias a @Ozesh por sus comentarios, se solucionó el problema relacionado con las propiedades con valores falsos .